<?php

namespace Home\Controller;

use Home\Biz\DealerBiz;
use Think\Controller;
use Home\Biz\StringBiz;
use Home\Biz\OrderBiz;
use Home\Biz\OtmsBiz;
use Home\Biz\MailBiz;
use Home\Biz\SaleBiz;
use Home\Biz\CommonBiz;
use Home\Biz\RmaBiz;
use Home\Biz\OrderInfoBiz;

class DealerController extends LoginBaseController {
	public function partofexpressdetail() {
		

		$order_id = I ( 'order_id' );
		$oid = I ( 'oid' );
		$order_info_en = M ( 'order_info' )->where ( "order_id='%s'", $order_id )->find ();
		
		if (empty ( $order_info_en )) {
			$error_msg = "订单不存在!";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
			return;
		}
		
		if (empty ( $order_info_en ['ship_qty'] )) {
				
			$order_info_en ['ship_qty'] = 0;
		}
		
		if (empty ( $oid )) {
				
			$order_detail_list = M ( 'order_detail' )->where ( "order_id='%s'", $order_id )->select ();
			$this->assign ( "isPart", 1 );
		} else {
			// 部分发货逻辑
			$order_detail_list = M ( 'order_detail' )->where ( "order_id='%s' and oid='%s'", $order_id, $oid )->select ();
			$this->assign ( "isPart", 2 );
		}
		
		foreach ( $order_detail_list as &$order_detail ) {
				
			if (empty ( $order_detail ['ship_qty'] )) {
		
				$order_detail ['ship_qty'] = 0;
			}
		}
		
		$this->assign ( 'order_info_en', $order_info_en );
		$this->assign ( 'order_detail_list', $order_detail_list );
		$this->display ( 'dealer/partofexpress' );
	}
	public function partofexpressAction() {
	    $order_id = I ( 'order_id' );
		$isPart = I ( 'isPart' );
		$logistic_type = I ( 'logistic_type' );
		$logistic_name = I ( 'logistic_name' );
		$express_no = I ( 'express_no' );
		$send_date = I ( 'send_date' );
		if (empty ( $send_date )) {
			
			$send_date = date ( "y-m-d H:i:s", time () );
		}
		$remark = I ( 'remark' );
		$shipping_warehouse = I ( 'shipping_warehouse' );
		$order_info_en = M ( 'order_info' )->where ( "order_id='%s'", $order_id )->find ();
		
		if (empty ( $order_info_en )) {
			$error_msg = "订单不存在!";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
			return;
		}
		

		
		//余额支付扣钱逻辑（废弃，余额扣款前移至提交订单）
		//支付类型为余额支付且支付状态为未支付的经销商订单
//		if($order_info_en['payment_type'] ==3 &&$order_info_en['payment_status']==0 && $order_info_en ['order_status'] == 10 && $order_info_en ['order_type'] == 8){
//
//			//查看该经销商账户余额
//
//			$dealer_buyer_en= M('dealer_info')->where("dealer_id='%s'",$order_info_en['buyer_alipay_no'])->find();
//
//			if($dealer_buyer_en['amount']-$order_info_en['payment_amount'] <0){
//
//				$error_msg = "经销商余额不足,请先充值!";
//				redirect ( C ( 'AdminConfig.info_page' ) . '?type=202&is_show_button=2&msg=' . $error_msg );
//				return;
//			}
//
//			//扣款并更改相关状态
//			//扣经销商余额
//
//			M('dealer_info')->where("dealer_id='%s'",$order_info_en['buyer_alipay_no'])->setField('amount',$dealer_buyer_en['amount']-$order_info_en['payment_amount']);
//			//插入经销商余额表
//			$dealer_amount = array(
//					"dealer_amount_id"	=> DealerBiz::generateDealerAmountId(),
//					"dealer_id" =>$dealer_buyer_en['dealer_id'],
//					"dealer_name" =>$dealer_buyer_en['dealer_name'],
//					"amount_kind" =>2,//减少
//					"amount_type" =>24,//订单支付
//					"amount" =>$order_info_en['payment_amount'],//订单金额
//					"begin_amount" =>$dealer_buyer_en['amount'],
//					"end_amount" =>$dealer_buyer_en['amount']-$order_info_en['payment_amount'],
//					"order_id" => $order_info_en['order_id'],
//					"remark" =>"订单支付",
//					"status" =>1,//有效
//					'create_user' => "whaleyinfo.order DealerBiz.partofexpress",
//					'create_date' => date ( "y-m-d H:i:s", time () )
//			);
//
//			M('dealer_amount')->add($dealer_amount);
//
//			//更新订单状态为已支付并插入日志
//			$order_status_update =array(
//				'payment_method'	=>30,//余额支付
//				'payment_status' =>1,//已支付
//				'order_status' =>22 ,//已支付
//			);
//
//			M('order_info')->where("order_id='%s'",$order_info_en['order_id'])->setField($order_status_update);
//			$order_change_log = array (
//					"order_id" => $order_id,
//					"order_status" => 22,//支付
//					"order_status_text" => StringBiz::getPromoterOrderStatusText(22),
//					"create_user" => 'whaleyinfo.order dealer.partofexpress',
//					"create_date" => date ( "y-m-d H:i:s", time () )
//			);
//			M ( 'order_status_change_log' )->data ( $order_change_log )->add ();
//			//更新订单支付表支付状态
//			M('order_payment')->where("order_id='%s'",$order_info_en['order_id'])->setField("payment_status",1);
//		}

		
		// 必须重新查询订单状态
		$order_info_en = M ( 'order_info' )->where ( "order_id='%s'", $order_id )->find ();
		
		if ($isPart == 1) {
			
			// 1.检查经销商订单状态是否为已支付状态或者部分发货
			
			if (($order_info_en ['order_status'] == 33 || $order_info_en ['order_status'] == 22) && $order_info_en ['order_type'] == 8) {
				
				$order_detail_list = M ( 'order_detail' )->where ( "order_id='%s'  ", $order_id )->select ();
				
				//剩余的待发明细
				$order_detail_left_list = M ( 'order_detail' )->where ( "order_id='%s'  and  qty!= ship_qty and qty !=rma_qty ", $order_id )->select ();
				//$order_info_en ['ship_qty'] = $order_info_en ['goods_qty'];
				// 订单状态为全部发货
				$order_info_en ['order_status'] = 31;
				
				foreach ( $order_detail_left_list as &$order_detail ) {
					// 更新订单明细实发数量生成插入物流信息并写入数据库
					if (empty ( $order_detail ['ship_qty'] )) {
						
						$order_detail ['ship_qty'] = 0;
					}
					
				
						
						$order_consign = array (
									
								'order_logistic_id' => CommonBiz::getExpressId ( "Express" ),
								'order_id' => $order_info_en ['order_id'],
								'oid' => $order_detail ['oid'],
								// 实发数量是总数减去已发货的数量
								'ship_qty' => $order_detail ['qty'] - $order_detail ['ship_qty'],
								'logistic_type' => $logistic_type,
								'logistic_name' => $logistic_name,
								'express_no' => $express_no,
								'shipping_warehouse' => $shipping_warehouse,
								'send_date' => $send_date,
								'remark' => $remark,
								'create_user' => "whaleyinfo.order DealerBiz.partofexpress",
								'create_date' => date ( "y-m-d H:i:s", time () )
						);
							
						$order_detail ['ship_qty'] = $order_detail ['qty'];
						
						$order_info_en ['ship_qty'] += $order_detail ['qty'];
						M ( 'order_consignment' )->add ( $order_consign );
						M ( 'order_detail' )->where ( "order_id='%s' and oid='%s'", $order_id, $order_detail ['oid'] )->save ( $order_detail );
					
				}
				
				// 写订单数据库
				M ( 'order_info' )->where ( "order_id='%s'", $order_id )->save ( $order_info_en );
				// 写订单日志表
				$order_change_log = array (
						"order_id" => $order_id,
						"order_status" => 31,
						"order_status_text" => '全部发货',
						"create_user" => 'whaleyinfo.order dealer.partofexpress',
						"create_date" => date ( "y-m-d H:i:s", time () ) 
				);
				M ( 'order_status_change_log' )->data ( $order_change_log )->add ();
				
				$succ_msg = "订单全部发货操作成功!";
				redirect ( C ( 'AdminConfig.info_page' ) . '?type=202&is_show_button=2&msg=成功,' . $succ_msg );
				return;
			} else {
				
				$error_msg = "订单状态非法,全部发货操作仅限于已支付的经销商订单!";
				redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
				return;
			}
		} elseif ($isPart == 2) {
			
			$ship_qty = I ( 'ship_qty' );
			$order_detail_id = I ( 'order_detail_id' );
			
			// 检查经销商订单为部分发货或者已支付状态
			if (($order_info_en ['order_status'] == 33 || $order_info_en ['order_status'] == 22) && $order_info_en ['order_type'] == 8) {
				
				$order_detail_audit = M ( 'order_detail' )->where ( "order_id='%s' and oid='%s'", $order_id, $order_detail_id )->find ();
				//全部明细
				$order_detail_list = M ( 'order_detail' )->where ( "order_id='%s' ", $order_id )->select ();
				//剩余的待发明细
				$order_detail_left_list = M ( 'order_detail' )->where ( "order_id='%s'  and  qty!= ship_qty and qty !=rma_qty ", $order_id )->select ();
				// 判断该订单明细是否存在
				if (empty ( $order_detail_audit )) {
					
					$error_msg = "该订单明细不存在!";
					redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
					return;
				}
				
				
				// 判断该订单明细提交的发货数量是否合法
				
				if (empty ( $order_detail_audit ['ship_qty'] )) {
					
					$order_detail_audit ['ship_qty'] = 0;
				}
				
				if (empty ( $order_info_en ['ship_qty'] )) {
					
					$order_info_en ['ship_qty'] = 0;
				}
				
				if (($order_detail_audit ['qty'] - $order_detail_audit ['ship_qty']) <= 0) {
					
					$error_msg = "该订单明细没有剩余待发的货物数量!";
					redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
					return;
				} elseif ($ship_qty > ($order_detail_audit ['qty'] - $order_detail_audit ['ship_qty'])) {
					
					$error_msg = "发货的数量大于该订单明细剩余待发的货物数量!";
					redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
					return;
				} else {
					
					// 该订单明细正常走正常发货流程
					// 更新该订单明细实发的数量，累加
					
					$order_detail_audit ['ship_qty'] = $order_detail_audit ['ship_qty'] + $ship_qty;
					
					// 根据订单明细更改订单状态已及发货的数量
					// 计算已发的总的数量,已累计本次提交的数据
					$total_shipqty = 0;
					foreach ( $order_detail_list as &$order_detail ) {
						
						if (empty ( $order_detail ['ship_qty'] )) {
							
							$order_detail ['ship_qty'] = 0;
						}
						
						if ($order_detail ['oid'] == $order_detail_id) {
							
							$total_shipqty = $order_detail_audit ['ship_qty'] + $total_shipqty;
						} else {
							
							$total_shipqty = $order_detail ['ship_qty'] + $total_shipqty;
						}
					}
					
					// 判断订单状态
					if ($total_shipqty > $order_info_en ['goods_qty']) {
						$error_msg = "发货的数量大于该订单剩余待发的货物数量!";
						redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
						return;
					} elseif (sizeof($order_detail_left_list) == 1||$order_info_en['goods_qty']==$total_shipqty) {
						// 全部发货
						$order_info_en ['ship_qty'] = $total_shipqty;
						// 订单状态为全部发货
						$order_info_en ['order_status'] = 31;
					} else {
						// 部分发货
						$order_info_en ['ship_qty'] = $total_shipqty;
						// 订单状态为部分发货
						$order_info_en ['order_status'] = 33;
					}
					
					$order_consign = array (
							
							'order_logistic_id' => CommonBiz::getExpressId ( "Express" ),
							'order_id' => $order_info_en ['order_id'],
							'oid' => $order_detail_audit ['oid'],
							'ship_qty' => $ship_qty,
							'logistic_type' => $logistic_type,
							'logistic_name' => $logistic_name,
							'express_no' => $express_no,
							'shipping_warehouse' => $shipping_warehouse,
							'send_date' => $send_date,
							'remark' => $remark,
							'create_user' => "whaleyinfo.order DealerBiz.partofexpress",
							'create_date' => date ( "y-m-d H:i:s", time () ) 
					);
					
					$order_change_log = array (
							"order_id" => $order_id,
							"order_status" => $order_info_en ['order_status'],
							"order_status_text" => StringBiz::getPromoterOrderStatusText ( $order_info_en ['order_status'] ),
							"create_user" => 'whaleyinfo.order dealer.partofexpress',
							"create_date" => date ( "y-m-d H:i:s", time () ) 
					);
					M ( 'order_info' )->where ( "order_id='%s'", $order_id )->save ( $order_info_en );
					M ( 'order_detail' )->where ( "order_id='%s' and oid='%s'", $order_id, $order_detail_audit ['oid'] )->save ( $order_detail_audit );
					M ( 'order_consignment' )->add ( $order_consign );
					M ( 'order_status_change_log' )->data ( $order_change_log )->add ();
					
					$succ_msg = "订单部分发货操作成功!";
					redirect ( C ( 'AdminConfig.info_page' ) . '?type=202&is_show_button=2&msg=成功,' . $succ_msg );
					return;
				}
			} else {
				
				$error_msg = "订单状态非法,部分发货操作仅限于已经处于部分发货或者已支付的经销商订单!";
				redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
				return;
			}
		} else {
			$error_msg = "操作流程不合规,请检查";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
			return;
		}
	}
	public function detail() {
		$order_id = I ( 'order_id' );

        // ============= 订单信息构建 Begin =============

        $order_info_en = M ( 'order_info' )->where ( "order_id='%s'", $order_id )->find ();
        $order_info_en ['order_status_text'] = StringBiz::getPromoterOrderStatusText ( $order_info_en ['order_status'] );
        $order_info_en ['order_type_text'] = StringBiz::getOrderTypeText ( $order_info_en ['order_type'] );
        $order_info_en ['payment_type_text'] = StringBiz::getPaymentTypeText ( $order_info_en ['payment_type'] );
        $order_info_en ['payment_method_text'] = StringBiz::getPaymentMethodText ( $order_info_en ['payment_method'] );


        $order_discount_en = M ( 'order_discount' )->where ( "order_id='%s' AND discount_type=41", $order_id )->find ();
		$order_payment_en = M ( 'order_payment' )->where ( "order_id='%s'", $order_id )->find ();
		$order_detail_en = M ( 'order_detail' )->where ( "order_id='%s'", $order_id )->select ();

		
		$order_consign_en = M ( 'order_consignment' )->alias('oc')->where ( "oc.order_id='%s'", $order_id )->join("order_detail od on od.order_id=oc.order_id  and od.oid= oc.oid")->select ();
		$order_change_log_en = M ( 'order_status_change_log' )->where ( "order_id='%s'", $order_id )->order ( "create_date desc" )->select ();
		
		// 取消订单实体begin
		$lst_order_canel_en = M ( 'order_cancel' )->where ( "order_id='%s'", $order_id )->order ( "create_date desc" )->select ();
		if (! empty ( $lst_order_canel_en )) {
			foreach ( $lst_order_canel_en as $key => $order_canel_en ) {
				$lst_order_canel_en [$key] ['role_user_text'] = '【' . StringBiz::getOrderCanelRoleTypeText ( $order_canel_en ['role_type'] ) . '】' . $order_canel_en ['role_user_id'];
				$lst_order_canel_en [$key] ['cancel_reason_text'] = StringBiz::getOrderCanelCancelReasonText ( $order_canel_en ['cancel_reason'] );
			}
		}
		// 取消订单实体end


		//订单部分取消
		 $lst_order_part_cancel=M('order_rma')->alias('orm')->Field('ord.sku_id,ord.sku_name,ord.rma_qty,ord.create_date,orm.rma_reason_remark')->join("order_rma_detail ord on orm.order_rma_id = ord.order_rma_id")->where("orm.order_id='%s' and orm.rma_reason_type=3 ",$order_id)->select();
		
		

		if (empty ( $order_info_en ['ship_qty'] )) {
			
			$order_info_en ['ship_qty'] = 0;
		}
		
		foreach ( $order_detail_en as &$order_detail ) {
			
			if (empty ( $order_detail ['ship_qty'] )) {
				
				$order_detail ['ship_qty'] = 0;
			}
			
			if (empty ( $order_detail ['rma_qty'] )) {
			
				$order_detail ['rma_qty'] = 0;
			}
			
			if(($order_detail['qty']!=$order_detail ['ship_qty'])&&($order_detail['qty']!=$order_detail ['rma_qty']) ){
				//未发货且未退货
				$order_detail['is_button_show_cancl_and_deliver']=1;
							
			}else{
				$order_detail['is_button_show_cancl_and_deliver']=0;
			}
			$lst_order_invoice = M ( 'dealer_order_invoice' )->Field("invoice_no,invoice_code")->where ( "oid='%s'", $order_detail['oid'] )->select ();
			if(sizeof($lst_order_invoice) > 0){
				$order_inv_nos = array();
				foreach($lst_order_invoice as $order_inv){
					if(!empty($order_inv['invoice_no']) && !empty($order_inv['invoice_code'])){
						array_push($order_inv_nos, ($order_inv['invoice_no'].'【' . $order_inv['invoice_code'] . '】'));
					}
				}
				$order_detail['invoice_nos'] = implode("<br/>",$order_inv_nos);
			}
		}
        // ============= 订单信息构建 End =============



        // ============= 判断界面上的按钮的显示 Begin =============
        //取消订单按钮
        if(in_array($order_info_en['order_status'], array(10,11,12,14,15,21,22,23))){
            $this->assign ( 'is_button_show_cancl_order', 1);
        }
        else{
            $this->assign ( 'is_button_show_cancl_order', 0);
        }

        //上传支付凭证按钮
        if($order_info_en['payment_type'] == 4
            && in_array($order_info_en['order_status'], array(10,23))
        ){
            $this->assign ( 'is_button_show_upload_payment', 1);
        }
        else{
            $this->assign ( 'is_button_show_upload_payment', 0);
        }

        //销售审批按钮
        $is_button_show_seller_audit = 0;

        if($order_info_en['payment_type'] == 3)
        {
            if(in_array($order_info_en['order_status'], array(10))){
                $is_button_show_seller_audit = 1;
            }
        }
        if($order_info_en['payment_type'] == 4)
        {
            if(in_array($order_info_en['order_status'], array(16, 23))){
                $is_button_show_seller_audit = 1;
            }
        }
        $this->assign ( 'is_button_show_seller_audit', $is_button_show_seller_audit);

        //财务审批按钮
        $is_button_show_finance_audit = 0;

        if(in_array($order_info_en['order_status'], array(14))){
            $is_button_show_finance_audit = 1;
        }
        $this->assign ( 'is_button_show_finance_audit', $is_button_show_finance_audit);

        // ============= 判断界面上的按钮的显示 End =============

        //新增物流信息查询功能
        $logistics_info = OtmsBiz::logistics4TreeGrid($order_id);//EPI101182889
        $this->assign('logistics_info', $logistics_info);
        
		$this->assign ( 'order_info_en', $order_info_en );
		$discount_amount = $order_discount_en [discount_amount];
		$this->assign ( 'discount_amount', abs ( $discount_amount ) );
		$this->assign ( 'order_payment_en', $order_payment_en );
		$this->assign ( 'order_detail_en', $order_detail_en );
		$this->assign ( "order_consign_en", $order_consign_en );
		$this->assign ( "order_change_log_en", $order_change_log_en );
		$this->assign ( "lst_order_canel_en", $lst_order_canel_en );
		$this->assign ( "lst_order_part_cancel", $lst_order_part_cancel );
		
		$this->assign ( 'page_name', '订单明细' );
		$this->display ( 'dealer/dealerOrderDetail_V2' );
	}
	public function paymentVoucherUpload() {
		$order_id = I ( 'order_id' );
		$this->assign ( 'order_id', $order_id );
		$this->display ( 'dealer/paymentVoucherUpload' );
	}
	public function paymentVoucherUploadAction() {
		$order_id = I ( 'order_id' );
		
		/**
		 * * 图片上传 start **
		 */
		$upload_config = array (
				'maxSize' => 0,
				'rootPath' => './Public/Uploads/',
				'savePath' => 'paymentVoucher/' . $order_id . '/',
				'saveName' => array (
						'uniqid',
						'' 
				),
				'exts' => array (
						'jpg',
						'gif',
						'png',
						'jpeg' 
				),
				'subName' => '',
				'replace' => true 
		);
		
		$upload->autoSub = false;
		$upload = new \Think\Upload ( $upload_config ); // 实例化上传类
		
		$info = $upload->upload ();
		if (! $info) {
			// 转到注册失败页面
			echo $upload->getError ();
			return;
		} else {
			foreach ( $info as $file ) {
				$key = $file ['key'];
				switch ($key) {
					case 'img_payment_voucher' :
						$payment_voucher = $file ['savepath'] . $file ['savename'];
					default :
						break;
				}
			}
		}
		/**
		 * * 图片上传 end **
		 */
		
		$error_msg = M ( 'order_payment' )->where ( "order_id='%s'", $order_id )->setField ( 'payment_voucher', $payment_voucher );
		
		if (! $error_msg) {
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=201&is_show_button=2&msg=,更新订单支付凭证失败。' . $error_msg );
			return;
		} else {
			M ( 'order_info' )->where ( "order_id='$order_id'" )->setField ( 'order_status', '23' );
			MailBiz::callMailApi ( C ( 'EmailConfig.PaymentVoucherUploadReceiverList' ), '经销商渠道订单' . $order_id . C ( 'EmailConfig.PaymentVoucherUploadMailSubject' ), '经销商渠道订单' . $order_id . C ( 'EmailConfig.PaymentVoucherUploadMailSubject' ) );
			redirect ( C ( 'AdminConfig.info_page' ) . '?type=201&is_show_button=2&msg=订单支付凭证上传成功。' );
			return;
		}
	}
	public function addDealer() {
		$this->assign ( 'page_name', '经销商信息添加' );
		$this->display ( 'dealer/adddealer' );
	}
	public function stockOrderImport() {
		$this->assign ( 'page_name', '订单导入' );
		$this->display ( 'dealer/stockOrderImport' );
	}
	public function stockOrderImportAction() {
		$upload_config = array (
				'maxSize' => 0,
				'rootPath' => './Public/Uploads/',
				'savePath' => 'k3_code_order_import/',
				'saveName' => 'order_import',
				'exts' => array (
						'xls' 
				),
				'subName' => '',
				'replace' => true 
		);
		
		$upload = new \Think\Upload ( $upload_config ); // 实例化上传类
		$upload->autoSub = false;
		
		$info = $upload->upload ();
		if (! $info) {
			// 上传错误提示错误信息
			redirect ( 'dealerOrderUploadResult?msg=上传失败！' . $upload->getError () );
		} else {
			// 上传成功
			// 读取csv文件将相关数据写入数据库
			// $xls_file = fopen('./Public/Uploads/stockOrderImport/stockOrderImport.xls','r');
			$err_msg = DealerBiz::k3_coder_order_import ( './Public/Uploads/k3_code_order_import/order_import.xls' );
			if (! empty ( $err_msg )) {
				//redirect ( 'dealerOrderUploadResult?msg=已成功上传并处理！共有' . $err_msg [total_row] . "条记录，成功" . $err_msg [success] . "条记录，失败" . $err_msg [failure] . "条记录。"."失败的经销商名单：" .$err_msg[error_dealers]);
				$this->assign("msg",json_encode($err_msg));
				$this->display("dealer/dealerOrderUploadResult");
				
			}
		}
	}
	public function updateDealerAction() {
		$dealer_id = I ( 'dealer_id' );
		$sign_date = I ( 'sign_date' );
		$contract_start_date = I ( 'contract_start_date' );
		$contract_end_date = I ( 'contract_end_date' );
		
		if (empty ( $sign_date )) {
			$sign_date = null;
		} else {
			
			$sign_date = date ( "y-m-d H:i:s", strtotime ( $sign_date ) );
		}
		
		if (empty ( $contract_start_date )) {
			$contract_start_date = null;
		} else {
			
			$contract_start_date = date ( "y-m-d H:i:s", strtotime ( $contract_start_date ) );
		}
		
		if (empty ( $contract_end_date )) {
			$contract_end_date = null;
		} else {
			
			$contract_end_date = date ( "y-m-d H:i:s", strtotime ( $contract_end_date ) );
		}
		
		$is_exists_dealer = M ( 'dealer_info' )->where ( "dealer_name='%s' and dealer_channel=1 and dealer_id!='%s'", I ( 'dealer_name' ), I ( 'dealer_id' ) )->find ();
		if (! empty ( $is_exists_dealer )) {
			$error_msg = "VR渠道经销商已存在!";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&msg=,' . $error_msg );
			return;
		}
		
		$update_dealer_en = array (
				'dealer_id' => $dealer_id,
				'dealer_name' => I ( 'dealer_name' ),
				'dealer_type' => I ( 'dealer_type' ),
				'k3_code' => I ( 'k3_code' ),
				'user_id' => I ( 'user_id_fk' ),
				'discount_rate' => I ( 'discount_rate' ),
				'cash_back_rate' => I ( 'cash_back_rate' ),
				'business_leader' => I ( 'business_leader' ),
				'business_leader_cellphone' => I ( 'business_leader_cellphone' ),
				'area_name' => I ( 'area_name' ),
				'province_id' => I ( 'province_id' ),
				'province_name' => I ( 'province_name' ),
				'city_id' => I ( 'city_id' ),
				'city_name' => I ( 'city_name' ),
				'operation_pattern' => I ( 'operation_pattern' ),
				'registered_capital' => I ( 'registered_capital' ),
				'leal_person' => I ( 'leal_person' ),
				'bank_name' => I ( 'bank_name' ),
				'bank_no' => I ( 'bank_no' ),
				'tax_no' => I ( 'tax_no' ),
				'dealer_id_card_no' => I ( 'dealer_id_card_no' ),
				'dealer_id_card_image_list' => I ( 'dealer_id_card_image_list' ),
				'business_license_image' => I ( 'business_license_image' ),
				'business_license_no' => I ( 'business_license_no' ),
				'finance_leader' => I ( 'finance_leader' ),
				'finance_leader_cellphone' => I ( 'finance_leader_cellphone' ),
				'invoice_address' => I ( 'invoice_address' ),
				'registered_address' =>I('registered_address'),
				'registered_tel' =>I('registered_tel'),
				'remark' => I ( 'remark' ),
				'sign_status' => I ( 'sign_status' ),
				'sign_date' => $sign_date,
				'contract_start_date' => $contract_start_date,
				'contract_end_date' => $contract_end_date,
				'status' => 1, // 待审核状态
				'update_user' => "whaleyinfo.order DealerController.updateDealerAction",
				'update_date' => date ( "y-m-d H:i:s", time () ) 
		);
		
		$upload_config = array (
				'maxSize' => 2 * 1024 * 1024,
				'rootPath' => './Public/Uploads/',
				'savePath' => 'dealer/' . $dealer_id . '/',
				'saveName' => array (
						'uniqid',
						'' 
				),
				'exts' => array (
						'jpg',
						'gif',
						'png',
						'jpeg' 
				),
				'subName' => '',
				'replace' => true 
		);
		$upload->autoSub = false;
		$upload = new \Think\Upload ( $upload_config ); // 实例化上传类
		
		$info = $upload->upload ();
		
		$upload_image_array = array ();
		
		foreach ( $info as $file ) {
			
			$key = $file ['key'];
			$upload_image_array ['path'] = $file ['savepath'] . $file ['savename'];
			switch ($key) {
				case 'dealer_id_card_image_list1' :
					
					if (empty ( $update_dealer_en ['dealer_id_card_image_list'] )) {
						$update_dealer_en ['dealer_id_card_image_list'] = $file ['savepath'] . $file ['savename'];
					} else {
						$id_images = explode ( "|", $update_dealer_en ['dealer_id_card_image_list'] );
						
						$update_dealer_en ['dealer_id_card_image_list'] = $file ['savepath'] . $file ['savename'] . '|' . $id_images [1];
					}
					
					break;
				case 'dealer_id_card_image_list2' :
					
					if (empty ( $update_dealer_en ['dealer_id_card_image_list'] )) {
						$update_dealer_en ['dealer_id_card_image_list'] = $file ['savepath'] . $file ['savename'];
					} else {
						$id_images = explode ( "|", $update_dealer_en ['dealer_id_card_image_list'] );
						$update_dealer_en ['dealer_id_card_image_list'] = $id_images [0] . '|' . $file ['savepath'] . $file ['savename'];
					}
					break;
				case 'business_license_image1' :
					
					$update_dealer_en ['business_license_image'] = $file ['savepath'] . $file ['savename'];
					break;
				
				case 'organization_image1' :
					
					$update_dealer_en ['organization_image'] = $file ['savepath'] . $file ['savename'];
					break;
				case 'tax_registration_image1' :
					
					$update_dealer_en ['tax_registration_image'] = $file ['savepath'] . $file ['savename'];
					break;
				case 'general_taxpayer_image1' :
					
					$update_dealer_en ['general_taxpayer_image'] = $file ['savepath'] . $file ['savename'];
					break;
				case 'account_opening_image1' :
					
					$update_dealer_en ['account_opening_image'] = $file ['savepath'] . $file ['savename'];
					break;
				
				default :
					break;
			}
		}
		
		// 上传完成
		
		// 添加dealer已及user信息
		
		DealerBiz::updateDealer ( $update_dealer_en );
		
		$info_msg = "经销商信息更新成功！";
		redirect ( C ( 'AdminConfig.info_page' ) . '?type=202&msg=成功,' . $info_msg );
		
		return;
	}
	public function addDealerAction() {
		$dealer_id = DealerBiz::generateDealerId ();
		$user_id = DealerBiz::generateUserId ();
		$sign_date = I ( 'sign_date' );
		$contract_start_date = I ( 'contract_start_date' );
		$contract_end_date = I ( 'contract_end_date' );
		$status = I ( 'status' );
		
		if (empty ( $sign_date )) {
			$sign_date = null;
		} else {
			
			$sign_date = date ( "y-m-d H:i:s", strtotime ( $sign_date ) );
		}
		
		if (empty ( $contract_start_date )) {
			$contract_start_date = null;
		} else {
			
			$contract_start_date = date ( "y-m-d H:i:s", strtotime ( $contract_start_date ) );
		}
		
		if (empty ( $contract_end_date )) {
			$contract_end_date = null;
		} else {
			
			$contract_end_date = date ( "y-m-d H:i:s", strtotime ( $contract_end_date ) );
		}
		
		$cash_back_rate =I ( 'cash_back_rate' );
		if(empty($cash_back_rate)){
			$cash_back_rate=0;
		}
		
		$add_dealer_en = array (
				'dealer_id' => $dealer_id,
				'dealer_name' => I ( 'dealer_name' ),
				'dealer_type' => I ( 'dealer_type' ),
				'dealer_channel' => I ( 'dealer_channel' ),
				'k3_code' => I ( 'k3_code' ),
				'user_id' => $user_id,
				'discount_rate' => I ( 'discount_rate' ),
				'cash_back_rate' => $cash_back_rate,
				'business_leader' => I ( 'business_leader' ),
				'business_leader_cellphone' => I ( 'business_leader_cellphone' ),
				'area_name' => I ( 'area_name' ),
				'province_id' => I ( 'province_id' ),
				'province_name' => I ( 'province_name' ),
				'city_id' => I ( 'city_id' ),
				'city_name' => I ( 'city_name' ),
				'operation_pattern' => I ( 'operation_pattern' ),
				'registered_capital' => I ( 'registered_capital' ),
				'leal_person' => I ( 'leal_person' ),
				'bank_name' => I ( 'bank_name' ),
				'bank_no' => I ( 'bank_no' ),
				'tax_no' => I ( 'tax_no' ),
				'dealer_id_card_no' => I ( 'dealer_id_card_no' ),
				'business_license_no' => I ( 'business_license_no' ),
				'finance_leader' => I ( 'finance_leader' ),
				'finance_leader_cellphone' => I ( 'finance_leader_cellphone' ),
				'invoice_address' => I ( 'invoice_address' ),
				'registered_address' =>I('registered_address'),
				'registered_tel' =>I('registered_tel'),
				'remark' => I ( 'remark' ),
				'sign_status' => I ( 'sign_status' ),
				'sign_date' => $sign_date,
				'contract_start_date' => $contract_start_date,
				'contract_end_date' => $contract_end_date,
				'amount' => 0,
				'status' => 1,
				'create_user' => "whaleyinfo.order DealerBiz.addDealer",
				'create_date' => date ( "y-m-d H:i:s", time () ) 
		);
		
		$is_exists_dealer = M ( 'dealer_info' )->where ( "dealer_name='%s' and dealer_channel=1", I ( 'dealer_name' ) )->find ();
		if (! empty ( $is_exists_dealer )) {
			$error_msg = "经销商已存在!";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&msg=,' . $error_msg );
			return;
		}
		
		$upload_config = array (
				'maxSize' => 0,
				'rootPath' => './Public/Uploads/',
				'savePath' => 'dealer/' . $dealer_id . '/',
				'saveName' => array (
						'uniqid',
						'' 
				),
				'exts' => array (
						'jpg',
						'gif',
						'png',
						'jpeg' 
				),
				'subName' => '',
				'replace' => true 
		);
		$upload->autoSub = false;
		$upload = new \Think\Upload ( $upload_config ); // 实例化上传类
		$info = $upload->upload ();
		
		$upload_image_array = array ();
		if (! $info) {
			// 转到注册失败页面
			// redirect(C('UrlConfig.common_error_url').'?type=11&param=缺少证件照片上传(图片过大，不要超过2mb)，'.$upload->getError());
			// $error_msg="请上传文件大小不超过2M并以jpg,gif,png,jpeg格式的图片！";
			$error_msg = $upload->getError ();
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&msg=,' . $error_msg );
			return;
		}
		$req_image_list = array (
				"dealer_id_card_image_list1",
				"dealer_id_card_image_list2",
				"business_license_image1" 
		);
		
		$real_image_list = array ();
		
		foreach ( $info as $file ) {
			
			$key = $file ['key'];
			$upload_image_array ['path'] = $file ['savepath'] . $file ['savename'];
			switch ($key) {
				case 'dealer_id_card_image_list1' :
					
					array_push ( $real_image_list, "dealer_id_card_image_list1" );
					
					if (empty ( $add_dealer_en ['dealer_id_card_image_list'] )) {
						$add_dealer_en ['dealer_id_card_image_list'] = $file ['savepath'] . $file ['savename'];
					} else {
						$add_dealer_en ['dealer_id_card_image_list'] = $add_dealer_en ['dealer_id_card_image_list'] . '|' . $file ['savepath'] . $file ['savename'];
					}
					
					break;
				case 'dealer_id_card_image_list2' :
					
					array_push ( $real_image_list, "dealer_id_card_image_list2" );
					if (empty ( $add_dealer_en ['dealer_id_card_image_list'] )) {
						$add_dealer_en ['dealer_id_card_image_list'] = $file ['savepath'] . $file ['savename'];
					} else {
						$add_dealer_en ['dealer_id_card_image_list'] = $add_dealer_en ['dealer_id_card_image_list'] . '|' . $file ['savepath'] . $file ['savename'];
					}
					break;
				case 'business_license_image1' :
					
					array_push ( $real_image_list, "business_license_image1" );
					$add_dealer_en ['business_license_image'] = $file ['savepath'] . $file ['savename'];
					break;
				case 'organization_image1' :
					
					$add_dealer_en ['organization_image'] = $file ['savepath'] . $file ['savename'];
					break;
				case 'tax_registration_image1' :
					
					$add_dealer_en ['tax_registration_image'] = $file ['savepath'] . $file ['savename'];
					break;
				case 'general_taxpayer_image1' :
					
					$add_dealer_en ['general_taxpayer_image'] = $file ['savepath'] . $file ['savename'];
					break;
				case 'account_opening_image1' :
					
					$add_dealer_en ['account_opening_image'] = $file ['savepath'] . $file ['savename'];
					break;
				default :
					break;
			}
		}
		
		// 上传完成
		
		// 判断必须上传的图片有没有全部上传
		
		// echo $real_image_list[0];
		// return;
		
		foreach ( $req_image_list as $req ) {
			
			$flag = FALSE;
			foreach ( $real_image_list as $real ) {
				if ($req == $real) {
					$flag = True;
					break;
				}
			}
			
			if (! $flag) {
				
				switch ($req) {
					
					case 'dealer_id_card_image_list1' :
						
						$error_msg = "请上传身份证正面!";
						redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&msg=,' . $error_msg );
						return;
						break;
					case 'dealer_id_card_image_list2' :
						
						$error_msg = "请上传身份证反面!";
						redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&msg=,' . $error_msg );
						return;
						break;
					case 'business_license_image1' :
						$error_msg = "请上传营业执照图片!";
						redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&msg=,' . $error_msg );
						return;
						break;
					
					default :
						break;
				}
				
				break;
			}
		}
		
		// 添加dealer已及user信息
		DealerBiz::addDealer ( $add_dealer_en );
		
		// 查看登录用户是否为业务员
		$sale_id = cookie ( 'login_user_id' );
		$sale_en = M ( 'sale_user' )->where ( "sale_name='%s'", $sale_id )->find ();
		// 业务员逻辑
		if (! empty ( $sale_en )) {
			
			SaleBiz::addDealerSaleRelationship ( $sale_en ['sale_id'], $dealer_id );
			$log = array (
					'sale_id' => $sale_id,
					'dealer_id' => $dealer_id,
					'operation' => 'add',
					'operator_id' => cookie ( 'login_user_id' ),
					'create_user' => "whaleyinfo.order DealerController.addDealerAction",
					'create_date' => date ( "y-m-d H:i:s", time () ) 
			);
			
			SaleBiz::addSaleDealerLog ( $log );
		}
		
		$log = array (
				
				'dealer_id' => $dealer_id,
				'operation' => 'add',
				'operator_id' => cookie ( 'login_user_id' ),
				'create_user' => "whaleyinfo.order DealerController.addDealerAction",
				'create_date' => date ( "y-m-d H:i:s", time () ) 
		);
		
		SaleBiz::addSaleDealerLog ( $log );
		
		$info_msg = "经销商信息添加成功！";
		redirect ( C ( 'AdminConfig.info_page' ) . '?type=202&msg=成功,' . $info_msg );
		
		return;
	}
	
	function http_get_json($url)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_TIMEOUT, 500);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_URL,$url);			
		$response = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		return array($httpCode, $response);
	}
	public function dealerInfo() {
		

		// 查看登录用户是否为业务员
		$sale_id = cookie ( 'login_user_id' );
		// $sale_id = 'USR11147258';
		$sale_en = M ( 'sale_user' )->where ( "sale_name='%s'", $sale_id )->find ();
		// 业务员逻辑
		if (! empty ( $sale_en )) {
			
			$this->assign ( "isBussiness", 1 );
		}
		
		$this->assign ( "page_name", "经销商信息列表" );
		$this->display ( 'dealer/dealerinfo' );
	}
	public function detailDealer() {
		$dealer_id = I ( 'dealer_id' );
		// $dealer_id = "DL100001";
		$dealer_en = M ( 'dealer_info' )->where ( "dealer_id='%s'", $dealer_id )->find ();
		
		if (empty ( $dealer_en )) {
			
			$error_msg = "该经销商信息不存在,请检查";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&msg=,' . $error_msg );
			return;
		} else {
			
			$id_images = explode ( "|", $dealer_en ['dealer_id_card_image_list'] );
			$dealer_en ['id_1'] = "/Public/Uploads/" . $id_images [0];
			$dealer_en ['id_2'] = "/Public/Uploads/" . $id_images [1];
			$dealer_en ['id_3'] = "/Public/Uploads/" . $dealer_en ['business_license_image'];
			$dealer_en ['id_4'] = "/Public/Uploads/" . $dealer_en ['organization_image'];
			$dealer_en ['id_5'] = "/Public/Uploads/" . $dealer_en ['tax_registration_image'];
			$dealer_en ['id_6'] = "/Public/Uploads/" . $dealer_en ['general_taxpayer_image'];
			$dealer_en ['id_7'] = "/Public/Uploads/" . $dealer_en ['account_opening_image'];
			$this->assign ( "dealer_en", $dealer_en );
			$this->assign ( "page_name", "经销商信息更新" );
			$this->display ( "dealer/detaildealer" );
		}
	}
	public function dealerbelongstosale() {
		$sale_id = I ( 'sale_id' );
		$sale_en = M ( 'sale_user' )->where ( "sale_id='%s'", $sale_id )->find ();
		
		if (empty ( $sale_en )) {
			
			$error_msg = "该业务员不存在,请检查";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=505&msg=,' . $error_msg );
			return;
		} else {
			
			$this->assign ( "sale_id", $sale_id );
			$this->assign ( "page_name", "业务员名下所有经销商" );
			$this->display ( "sale/dealersbelongstosale" );
		}
	}
	public function dealerinfoAuditPass() {
		$dealer_id = I ( 'dealer_id' );
		// $dealer_id = "DL100001";
		$dealer_en = M ( 'dealer_info' )->where ( "dealer_id='%s'", $dealer_id )->find ();
		
		if (empty ( $dealer_en )) {
			
			$error_msg = "该经销商信息不存在,请检查";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&msg=,' . $error_msg );
			return;
		} else {
			
			M ( 'dealer_info' )->where ( "dealer_id='%s'", $dealer_id )->setField ( "status", 2 );
			
			$info_msg = "经销商信息审批通过！";
			redirect ( C ( 'AdminConfig.info_page' ) . '?type=202&msg=成功,' . $info_msg );
			return;
		}
	}
	public function dealerinfoAuditFail() {
		$dealer_id = I ( 'dealer_id' );
		$remark = I ( 'remark' );
		
		// $dealer_id = "DL100001";
		$dealer_en = M ( 'dealer_info' )->where ( "dealer_id='%s'", $dealer_id )->find ();
		
		if (empty ( $dealer_en )) {
			
			$error_msg = "该经销商信息不存在,请检查";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&msg=,' . $error_msg );
			return;
		} elseif (empty ( $remark )) {
			$error_msg = "经销商信息审批失败,必须给出原因!";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&msg=,' . $error_msg );
			return;
		} 

		else {
			// 审批失败
			
			$update_dealer_info = array (
					'status' => 3,
					'remark' => $dealer_en ['remark'] . "|" . $remark 
			);
			
			M ( 'dealer_info' )->where ( "dealer_id='%s'", $dealer_id )->save ( $update_dealer_info );
			
			$error_msg = "" . $remark;
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&msg=,' . $error_msg );
			return;
		}
	}
	public function showDealer() {
		$dealer_id = I ( 'dealer_id' );
		// $dealer_id = "DL100001";
		$dealer_id = I ( 'dealer_id' );
		// $dealer_id = "DL100001";
		$dealer_info_en = M ( 'dealer_info' )->where ( "dealer_id='%s'", $dealer_id )->find ();
		
		if (empty ( $dealer_info_en )) {
			
			$error_msg = "该经销商信息不存在,请检查";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&msg=,' . $error_msg );
			return;
		} else {
			
			$dealer_info_en ['dealer_type_text'] = StringBiz::getDealerTypeRevenueStatusText ( $dealer_info_en ['dealer_type'] );
			$dealer_info_en ['status_text'] = StringBiz::getDealerStatusRevenueStatusText ( $dealer_info_en ['status'] );
			$dealer_info_en ['sign_status_text'] = StringBiz::getDealerSignStatusRevenueStatusText ( $dealer_info_en ['sign_status'] );
			$id_images = explode ( "|", $dealer_info_en ['dealer_id_card_image_list'] );
			$dealer_info_en ['id_1'] = "/Public/Uploads/" . $id_images [0];
			$dealer_info_en ['id_2'] = "/Public/Uploads/" . $id_images [1];
			$dealer_info_en ['id_3'] = "/Public/Uploads/" . $dealer_info_en ['business_license_image'];
			$dealer_info_en ['id_4'] = "/Public/Uploads/" . $dealer_info_en ['organization_image'];
			$dealer_info_en ['id_5'] = "/Public/Uploads/" . $dealer_info_en ['tax_registration_image'];
			$dealer_info_en ['id_6'] = "/Public/Uploads/" . $dealer_info_en ['general_taxpayer_image'];
			$dealer_info_en ['id_7'] = "/Public/Uploads/" . $dealer_info_en ['account_opening_image'];
			$user_addr_en = M ( 'user_address' )->where ( "user_id='%s'", $dealer_info_en ['user_id'] )->select ();
			$this->assign ( "dealer_info_en", $dealer_info_en );
			$this->assign ( "user_addr_en", $user_addr_en );
			$this->assign ( "page_name", "经销商信息明细" );
			$this->display ( 'dealer/showdealer' );
		}
	}
	
	/**
	 * ==================== 购物车begin ====================
	 */
	/**
	 * 老的下单流程
	 */
	public function dealerOrderCart() {
		$lst_product = M ( 'sku', '', 'DB_whaley_product' )->where ( "sku_channel =8 and status=1" )->select ();
		
		$this->assign ( "lst_product", $lst_product );
		$this->assign ( 'page_name', '经销商订单录入' );
		
		$address_user_id = I ( 'address_user_id' );
		
		if (! empty ( $address_user_id )) {
			$dealer_info_en = M ( 'dealer_info' )->where ( "user_id='%s'", $address_user_id )->find ();
			$this->assign ( 'param_dealer_id', json_encode ( $dealer_info_en ['dealer_id'] ) );
			$this->assign ( 'param_user_id', json_encode ( $dealer_info_en ['user_id'] ) );
			$this->assign ( 'param_dealer_name', json_encode ( $dealer_info_en ['dealer_name'] ) );
		} else {
			$this->assign ( 'param_dealer_id', json_encode ( '' ) );
			$this->assign ( 'param_user_id', json_encode ( '' ) );
			$this->assign ( 'param_dealer_name', json_encode ( '' ) );
		}
		
		$this->display ( 'dealer/dealerOrderCart' );
	}

    /**
     * 分步骤下单第一步选择经销商
     */
	public function dealerCartStep1(){
        $this->assign ( 'page_name', '选择经销商' );

        $lst_dealer_info    = array();
        $sale_id = cookie ( 'login_user_id' );
        $sale_en = M ( 'sale_user' )->where ( "sale_name='%s'", $sale_id )->find ();
        if (empty($sale_en)) {
            //非业务员有权限，加载所有可下单经销商
            $lst_dealer_info = M ( 'dealer_info' )->where ( "status=2" )->select ();
        }
        else{
            //业务员仅显示自己名下经销商
            $result = SaleBiz::queryDealerBySaleAndPara ( $sale_en ['sale_id'], '', '', '', '', null, 2, '',1,9999, 1 );
            $lst_dealer_info = $result ['datas'];
        }

        $this->assign ( "lst_dealer_info", $lst_dealer_info );
        $this->display ( 'dealer/dealerCartStep1' );
    }


    /**
     * 分步骤下单第二步选择地址和产品
     */
    public function dealerCartStep2()
    {
        $this->assign('page_name', '经销商录单购物车');


        //经销商信息
        $dealer_id  = I('dealer_id');
        $dealer_info_en = M ('dealer_info')->where("dealer_id='%s'", $dealer_id)->find();
        $this->assign('dealer_info_en', $dealer_info_en);


        //地址信息
        $lst_user_address_en    = M('userAddress')->where("user_id='%s'", $dealer_info_en['user_id'])->select();
        $this->assign('lst_user_address_en', $lst_user_address_en);


        //产品信息
        $lst_sku = M ('sku', '', 'DB_whaley_product')->where ("sku_channel =8 and status=1")->select();
        $this->assign("lst_sku", $lst_sku);


        $this->display('dealer/dealerCartStep2');
    }
    /**
     * ==================== 购物车end ====================
     */



	public function dealerinfosearch() {
		$dealer_name = I ( 'dealer_name' );
		$dealer_id = I ( 'dealer_id' );
		
		$con = array ();
		
		array_push ( $con, "status=2" );
		
		if (! empty ( $dealer_name )) {
			array_push ( $con, "dealer_name like '%$dealer_name%'" );
		}
		if (! empty ( $dealer_id )) {
			array_push ( $con, "dealer_id like '%$dealer_id%'" );
		}
		$lst_dealer_info = M ( 'dealer_info' )->where ( join ( " AND ", $con ) )->select ();
		
		$sale_id = cookie ( 'login_user_id' );
		$sale_en = M ( 'sale_user' )->where ( "sale_name='%s'", $sale_id )->find ();
		if ($sale_en == null) {
		} else {
			$result = SaleBiz::queryDealerBySaleAndPara ( $sale_en ['sale_id'], $dealer_name, '', '', '', null, 2, '', 1, 9999, 1 );
			$lst_dealer_info = $result ['datas'];
		}
		
		$this->assign ( "lst_dealer_info", $lst_dealer_info );
		
		$this->display ( 'dealer/dealerinfosearch' );
	}
	public function dealerOrderCheckout() {
        $this->assign ( "page_name", '提交订单');
		$dealer_id = I ( 'dealer_id' );
		$select_address_id = I ( 'select_address_id' );
		$sku_list_str = I ( 'sku_list_str' );
		$payment_type = I ( 'payment_type' );
		
		$dealer_en = M ( 'dealer_info' )->where ( "dealer_id='$dealer_id'" )->find ();
		$user_address = M ( 'user_address' )->where ( "address_id='$select_address_id'" )->find ();
		
		$lst_goods_info = explode ( "|", $sku_list_str );
		
		$goods_total_amount = 0;
        //$discount_total_amount = 0;//弃用
        $payment_total_amount = 0;
		
		$total_qty = 0;
		
		$lst_product = array ();
		
		// 计算商品总数，折扣总价
		foreach ( $lst_goods_info as $goods_info ) {
			
			$sku_str        = explode ( ",", $goods_info );
			$sku_id         = $sku_str [0];
			$qty            = intval ( $sku_str [1] );
            $payment_price  = floatval( ( $sku_str [2] ));
			if ($qty > 0) {
				$sku_en = M ( 'sku', '', 'DB_whaley_product' )->where ( "sku_id='$sku_id'" )->find ();
				$sku_en['qty']          = $qty;
                $sku_en['payment_price']= $payment_price;
				
				$sale_price = $sku_en ['sale_price'];
//				$discount_price = $sale_price;
//				if ($sku_en ['is_rebate'] == '1') {
//					$discount_price = $sale_price - $sale_price * $dealer_en ['discount_rate'];
//				}
//
//				$discount_price = round ( $discount_price, 2 );
//				$sku_en ['discount_price'] = $discount_price;
//				$sku_en ['discount_total_price']    = $discount_price * $qty;

                $sku_en ['payment_total_price']     = $payment_price * $qty;

                $total_qty              = $total_qty + $qty;
				$goods_total_amount     = $goods_total_amount + $sale_price * $qty;
//				$discount_total_amount  = $discount_total_amount + $discount_price * $qty;
                $payment_total_amount   = $payment_total_amount + $payment_price * $qty;
				
				array_push ( $lst_product, $sku_en );
			}
		}

		//计算可使用的余额与可使用的返利余额 begin
		$can_use_dealear_amount = 0;
        if($dealer_en['amount'] < $payment_total_amount){
            $can_use_dealear_amount = $dealer_en['amount'];
        }
        else{
            $can_use_dealear_amount = $payment_total_amount;
        }


        $can_use_dealear_cashback_amount = 0;
        if($dealer_en['cashback_amount'] < $payment_total_amount * 0.5){
            $can_use_dealear_cashback_amount = $dealer_en['cashback_amount'];
        }
        else{
            $can_use_dealear_cashback_amount = $payment_total_amount * 0.5;
        }
        //计算可使用的余额与可使用的返利余额 end

		$this->assign ( "total_qty", $total_qty );
		$this->assign ( "goods_total_amount", $goods_total_amount );
//		$this->assign ( "discount_total_amount", $discount_total_amount );
        $this->assign ( "payment_total_amount", $payment_total_amount );

        $this->assign ( "discount_amount", round($goods_total_amount - $payment_total_amount, 2));
		$this->assign ( "lst_product", $lst_product );
		$this->assign ( "dealer_en", $dealer_en );
		$this->assign ( "user_address", $user_address );
		$this->assign ( "dealer_id", $dealer_id );
		$this->assign ( "select_address_id", $select_address_id );
		$this->assign ( 'payment_type', $payment_type );
		$payment_type_text = CommonBiz::changePaymentType ( $payment_type );
		$this->assign ( 'payment_type_text', $payment_type_text );
		$this->assign ( "lst_sku", $sku_list_str );
        $this->assign ( "can_use_dealear_amount", $can_use_dealear_amount );
        $this->assign ( "can_use_dealear_cashback_amount", $can_use_dealear_cashback_amount );
		
		$this->display ( 'dealer/dealerOrderCheckout' );
	}
	public function dealerOrderSuccess() {
		$order_id = I ( 'order_id' );
		$this->assign ( "order_id", $order_id );
		$this->display ( 'dealer/dealerOrderSuccess' );
	}
	public function dealerOrderList() {
		$this->assign ( "page_name", "经销商订单列表" );
		$this->display ( 'dealer/dealerOrderInfo' );
	}
	public function dealerOrderDetail() {
		$this->display ( 'dealer/dealerOrderDetail' );
	}
	
	/**
	 * 上传page
	 */
	public function dealerUploadPage() {
		$this->display ( 'dealer/dealerOrderUpload' );
	}
	/**
	 * 经销商订单上传
	 */
	public function dealerStockOrderImportAction() {
		$upload_config = array (
				'maxSize' => 0,
				'rootPath' => './Public/Uploads/',
				'savePath' => 'stockOrderImport/',
				'saveName' => 'stockOrderImport',
				'exts' => array (
						'xls' 
				),
				'subName' => '',
				'replace' => true 
		);
		
		$upload = new \Think\Upload ( $upload_config ); // 实例化上传类
		$upload->autoSub = false;
		
		$info = $upload->upload ();
		if (! $info) {
			// 上传错误提示错误信息
			redirect ( 'dealerOrderUploadResult?msg=上传失败！' . $upload->getError () );
		} else {
			// 上传成功
			// 读取csv文件将相关数据写入数据库
			// $xls_file = fopen('./Public/Uploads/stockOrderImport/stockOrderImport.xls','r');
			$err_msg = DealerBiz::stockOrderImport ( './Public/Uploads/stockOrderImport/stockOrderImport.xls' );
			if (empty ( $err_msg )) {
				redirect ( 'dealerOrderUploadResult?msg=已成功上传并处理！' );
			} else {
				redirect ( "dealerOrderUploadResult?msg=$err_msg！" );
			}
		}
	}
	public function dealerOrderUploadResult() {
		$this->assign ( 'msg', I ( 'msg' ) );
		$this->display ( 'dealer/dealerOrderUploadResult' );
	}
	public function stockOrderImportResult() {
		$this->assign ( 'msg', I ( 'msg' ) );
		$this->display ( 'order/stockOrderImportResult' );
	}
	public function shipOrderExcel() {
		// 参数处理
		$params_en = array (
				'dealer_id' => I ( 'dealer_id' ),
				'dealer_name' => I ( 'dealer_name' ),
				'dealer_type' => I ( 'dealer_type' ),
				'order_id' => I ( 'order_id' ),
				'dealer_channel' => I ( 'dealer_channel' ),
				'order_status' => I ( 'order_status' ),
				'payment_status' => I ( 'payment_status' ),
				'order_startdate' => I ( 'start_date' ),
				'order_enddate' => I ( 'end_date' ) 
		);
		
		Vendor ( 'phpExcel.PHPExcel' );
		$objPHPExcel = OrderBiz::shipOrderExcel( $params_en );
		
		// 输出到浏览器
		// $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
		$objWriter = new \PHPExcel_Writer_Excel5 ( $objPHPExcel );
		
		header ( "Pragma: public" );
		header ( "Expires: 0" );
		header ( "Cache-Control:must-revalidate, post-check=0, pre-check=0" );
		header ( "Content-Type:application/force-download" );
		header ( "Content-Type:application/vnd.ms-execl" );
		header ( "Content-Type:application/octet-stream" );
		header ( "Content-Type:application/download" );
		header ( 'Content-Disposition:attachment;filename="result.xls"' );
		header ( "Content-Transfer-Encoding:binary" );
		$objWriter->save ( 'php://output' );
	}
	
	
	
	
	public function shipDealerInfoExcel() {
		// 参数处理
		$params_en = array (
				'dealer_name' => I ( 'dealer_name' ),
				'dealer_type' => I ( 'dealer_type' ),
				'business_leader' => I ( 'business_leader' ),
				'k3_code' => I ( 'k3_code' ),
				'area_name' => I ( 'area_name' ),
				'order_status' => I ( 'order_status' ),
				'sign_status' => I ( 'sign_status' ),
				'status' => I ( 'status' ),
				'dealer_channel' => I ( 'dealer_channel' )
		);
	
		Vendor ( 'phpExcel.PHPExcel' );
		$objPHPExcel = DealerBiz::shipDealerInfoExcel( $params_en );
	
		// 输出到浏览器
		// $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
		$objWriter = new \PHPExcel_Writer_Excel5 ( $objPHPExcel );
	    $export_name= "DealearInfo".date('y-m-d-H-i-s',time()).".xls";
		header ( "Pragma: public" );
		header ( "Expires: 0" );
		header ( "Cache-Control:must-revalidate, post-check=0, pre-check=0" );
		header ( "Content-Type:application/force-download" );
		header ( "Content-Type:application/vnd.ms-execl" );
		header ( "Content-Type:application/octet-stream" );
		header ( "Content-Type:application/download" );
		header ( "Content-Disposition:attachment;filename=".urlencode($export_name));
		header ( "Content-Transfer-Encoding:binary" );
		$objWriter->save ( 'php://output' );
	}
	
	
	public function dealersalseManagerAudit() {
		$order_id = I ( 'order_id' );
		$audit_type = I ( 'audit_type' );
		$errorMsg = "";
		$successMsg = "";
		
		$order_en = M ( 'order_info' )->where ( "order_id='%s'", $order_id )->find ();
		
		if (empty ( $order_en )) {
			$errorMsg = "订单不存在，请检查订单号！";
			$this->assign ( "order_id", $order_id );
			$this->assign ( "errorMsg", $errorMsg );
			$this->display ( "dealer/dealerauditerror" );
			return;
		}
		
		switch ($audit_type) {
			
			case 14 :
				// 销售管理部审批支付凭证已上传的订单
				if ($order_en ['order_status'] == 23||$order_en ['order_status'] == 16||$order_en ['order_status'] == 10) {
					// 改为14 order_info status, insert order_status_change_log
					M ( 'order_info' )->where ( "order_id='%s'", $order_id )->setField ( "order_status", 14 );
					$order_change_log = array (
							"order_id" => $order_id,
							"order_status" => 14,
							"order_status_text" => '销售管理部已审批',
							"create_user" => 'whaleyinfo.order dealer.dealerAudit',
							"create_date" => date ( "y-m-d H:i:s", time () ) 
					);
					M ( 'order_status_change_log' )->data ( $order_change_log )->add ();
					
					
					$order_fields = array (
							"order_status" => 15,
							"payment_status" => 1
					);
					M ( 'order_info' )->where ( "order_id='%s'", $order_id )->data ( $order_fields )->save ();
						
					if($order_en['payment_type'] != 3){
						$payment_fields = array (
								"payment_status" => 1,
								"payment_date" => date ( "y-m-d H:i:s", time () )
						);
						M ( 'order_payment' )->where ( "order_id='%s'", $order_id )->data ( $payment_fields )->save ();
					}
						
					$order_change_log = array (
							"order_id" => $order_id,
							"order_status" => 15,
							"order_status_text" => '财务经理已审批',
							"create_user" => 'whaleyinfo.order dealer.dealerAudit',
							"create_date" => date ( "y-m-d H:i:s", time () )
					);
					M ( 'order_status_change_log' )->data ( $order_change_log )->add ();
						
					// 财务经理审批完默认就是已经支付
					M ( 'order_info' )->where ( "order_id='%s'", $order_id )->setField ( "order_status", 22 );
					$order_change_log1 = array (
							"order_id" => $order_id,
							"order_status" => 22,
							"order_status_text" => '已支付',
							"create_user" => 'whaleyinfo.order dealer.dealerAudit',
							"create_date" => date ( "y-m-d H:i:s", time () )
					);
					M ( 'order_status_change_log' )->data ( $order_change_log1 )->add ();
					
					
					$successMsg = "销售管理部审批成功！";
					$this->assign ( "order_id", $order_id );
					$this->assign ( "successMsg", $successMsg );
					MailBiz::callMailApi ( C ( 'EmailConfig.AccountReceiverList' ), '经销商渠道订单' . $order_id . C ( 'EmailConfig.AccountReceiverMailSubject' ), '经销商渠道订单' . $order_id . C ( 'EmailConfig.AccountReceiverMailSubject' ) );
					$this->display ( "dealer/dealerauditsuccess" );
					
					return;
				} else {
					
					$errorMsg = "订单状态非法，请检查！";
					$this->assign ( "order_id", $order_id );
					$this->assign ( "errorMsg", $errorMsg );
					$this->display ( "dealer/dealerauditerror" );
					return;
				}
			
			default :
				$errorMsg = "操作非法，不符合审批流程！";
				$this->assign ( "order_id", $order_id );
				$this->assign ( "errorMsg", $errorMsg );
				$this->display ( "dealer/dealerauditerror" );
				return;
				break;
		}
	}
	
	public function dealerfinanceAudit() {
		$order_id = I ( 'order_id' );
		$audit_type = I ( 'audit_type' );
		$errorMsg = "";
		$successMsg = "";
		
		$order_en = M ( 'order_info' )->where ( "order_id='%s'", $order_id )->find ();
		
		if (empty ( $order_en )) {
			$errorMsg = "订单不存在，请检查订单号！";
			$this->assign ( "order_id", $order_id );
			$this->assign ( "errorMsg", $errorMsg );
			$this->display ( "dealer/dealerauditerror" );
			return;
		}
		
		switch ($audit_type) {
			
			case 15 :
				// 财务只处理订单状态为14即销售管理部已审批
				if ($order_en ['order_status'] == 14) {

					$order_fields = array (
							"order_status" => 15,
							"payment_status" => 1 
					);
					M ( 'order_info' )->where ( "order_id='%s'", $order_id )->data ( $order_fields )->save ();
					
					if($order_en['payment_type'] != 3){
						$payment_fields = array (						
								"payment_status" => 1,
								"payment_date" => date ( "y-m-d H:i:s", time () ) 
						);
						M ( 'order_payment' )->where ( "order_id='%s'", $order_id )->data ( $payment_fields )->save ();
					}
					
					$order_change_log = array (
							"order_id" => $order_id,
							"order_status" => 15,
							"order_status_text" => '财务经理已审批',
							"create_user" => 'whaleyinfo.order dealer.dealerAudit',
							"create_date" => date ( "y-m-d H:i:s", time () ) 
					);
					M ( 'order_status_change_log' )->data ( $order_change_log )->add ();
					
					// 财务经理审批完默认就是已经支付
					M ( 'order_info' )->where ( "order_id='%s'", $order_id )->setField ( "order_status", 22 );
					$order_change_log1 = array (
							"order_id" => $order_id,
							"order_status" => 22,
							"order_status_text" => '已支付',
							"create_user" => 'whaleyinfo.order dealer.dealerAudit',
							"create_date" => date ( "y-m-d H:i:s", time () ) 
					);
					M ( 'order_status_change_log' )->data ( $order_change_log1 )->add ();
					$successMsg = "财务经理审批成功！";
					$this->assign ( "order_id", $order_id );
					$this->assign ( "successMsg", $successMsg );
					$this->display ( "dealer/dealerauditsuccess" );
					MailBiz::callMailApi ( C ( 'EmailConfig.LogisticsReceiverList' ), '经销商渠道订单' . $order_id . C ( 'EmailConfig.LogisticsReceiverMailSubject' ), '经销商渠道订单' . $order_id . C ( 'EmailConfig.LogisticsReceiverMailSubject' ) );
					return;
				} else {
					
					$errorMsg = "订单状态非法，请检查";
					$this->assign ( "order_id", $order_id );
					$this->assign ( "errorMsg", $errorMsg );
					$this->display ( "dealer/dealerauditerror" );
					return;
				}
				case 16 :
					// 财务审批拒绝，订单状态为14即销售管理部已审批的订单。
					if ($order_en ['order_status'] == 14) {
						// 改为14 order_info status, insert order_status_change_log
						M ( 'order_info' )->where ( "order_id='%s'", $order_id )->setField ( "order_status", 16 );
						$order_change_log = array (
								"order_id" => $order_id,
								"order_status" => 16,
								"order_status_text" => '财务审批已拒绝',
								"remark" => I('remark'),
								"create_user" => 'whaleyinfo.order dealer.dealerAudit',
								"create_date" => date ( "y-m-d H:i:s", time () )
						);
						M ( 'order_status_change_log' )->data ( $order_change_log )->add ();
							
						$successMsg = "财务审批已拒绝成功！";
						$this->assign ( "order_id", $order_id );
						$this->assign ( "successMsg", $successMsg );
						MailBiz::callMailApi ( C ( 'EmailConfig.SaleReceiverList' ), '经销商渠道订单' . $order_id ."财务审批已拒绝", '经销商渠道订单' . $order_id . "财务审批已拒绝,需销售管理部检查该订单并重新审批.备注:".I('remark') );
						$this->display ( "dealer/dealerauditsuccess" );
							
						return;
					} else {
							
						$errorMsg = "订单状态非法，请检查！";
						$this->assign ( "order_id", $order_id );
						$this->assign ( "errorMsg", $errorMsg );
						$this->display ( "dealer/dealerauditerror" );
						return;
					}
			default :
				$errorMsg = "操作非法，不符合审批流程！";
				$this->assign ( "order_id", $order_id );
				$this->assign ( "errorMsg", $errorMsg );
				$this->display ( "dealer/dealerauditerror" );
				return;
				
		}
	}
	public function dealerAmountList() {
		$this->assign ( "page_name", "经销商余额列表" );
		$this->display ( "dealer/dealeramountchange" );
	}
	public function dealerCashBackAmountList() {
		$this->assign ( "page_name", "经销商后返余额列表" );
		$this->display ( "dealer/dealercashbackamountchange" );
	}
	public function dealerAmountAuditList() {
		$this->assign ( "page_name", "经销商余额审批列表" );
		$this->display ( "dealer/dealeramountauditlist" );
	}
	public function showDealerAmountRecharge() {
		$dealer_recharge_id = I ( 'dealer_recharge_id' );
		$recharge_en = M ( 'dealer_recharge' )->where ( "dealer_recharge_id='%s'", $dealer_recharge_id )->find ();
		if (empty ( $recharge_en )) {
			$error_msg = "该申请记录不存在!";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&msg=,' . $error_msg );
			return;
		}
		$dealer_en = M ( 'dealer_info' )->where ( "dealer_id='%s'", $recharge_en ['dealer_id'] )->find ();
		
		if (empty ( $dealer_en )) {
			
			$error_msg = "经销商不存在!";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&msg=,' . $error_msg );
			return;
		}
		
		$dealer_recharge_log=M('dealer_recharge_status_change_log')->where("dealer_recharge_id='%s' and recharge_status='%s'", $dealer_recharge_id,$recharge_en['recharge_status'])->find();
		
		$recharge_en ['recharge_status_text'] = StringBiz::getDealerRechargeTypeRevenueStatusText ( $recharge_en ['recharge_status'] );
		$recharge_en ['amount_kind_text'] = StringBiz::getDealerAmountKindRevenueStatusText ( $recharge_en ['amount_kind'] );
		$recharge_en ['amount_type_text'] = StringBiz::getDealerAmountTypeRevenueStatusText ( $recharge_en ['amount_type'] );
		$recharge_en ['identify_image'] = "/Public/Uploads/" . $recharge_en ['identify_image'];
		
		$this->assign ( "page_name", "经销商余额审批详情" );
		$this->assign ( "dealer_recharge_en", $recharge_en );
		$this->assign("dealer_recharge_log",$dealer_recharge_log);
		$this->display ( "dealer/showDealerAmountRecharge" );
	}
	public function dealerAmountApply() {
		$dealer_id = I ( 'dealer_id' );
		
		$is_exists_dealer = M ( 'dealer_info' )->where ( "dealer_id='%s'", $dealer_id )->find ();
		if (empty ( $is_exists_dealer )) {
			$error_msg = "经销商不存在!";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&msg=,' . $error_msg );
			return;
		}
		
		$this->assign ( "dealer_en", $is_exists_dealer );
		$this->display ( "dealer/dealeramountapply" );
		return;
	}
	public function dealerAmountApplyAction() {
		
		// 查看登录用户是否为业务员
		$sale_name = cookie ( 'login_user_id' );
		$sale_en = M ( 'sale_user' )->where ( "sale_name='%s'", $sale_name )->find ();
		// 业务员登录
		if (! empty ( $sale_en )) {
			
			$role_type = 2;
			$role_id = $sale_en ['sale_id'];
			$role_name = $sale_en ['sale_name'];
		} else {
			// 管理员角色
			$role_type = 1;
			$whaley_user = M ( 'whaley_user', '', 'DB_whaley_system' )->where ( "user_name='%s'", $sale_name )->find ();
			$role_id = $whaley_user ['user_id'];
			$role_name = $whaley_user ['user_name'];
		}
		
		$dealer_id = I ( 'dealer_id' );
		$dealer_en = M ( 'dealer_info' )->where( "dealer_id='%s'", $dealer_id )->find ();
		$dealer_recharge_id = DealerBiz::generateDealerAmountChargeId ();
		$add_dealer_recharge = array (
				'dealer_recharge_id' => $dealer_recharge_id,
				'dealer_id' => $dealer_id,
				'dealer_name' => I ( 'dealer_name' ),
				'audit_user_name' => cookie ( 'login_user_id' ),
				'amount_kind' => I ( 'amount_kind' ),
				'amount_type' => I ( 'amount_type' ),
				'amount' => I ( 'amount' ),
				'recharge_status' => 1,
				'remark' => I ( 'remark' ),
				'create_user' => "whaleyinfo.order DealerController.dealerAmountApplyAction",
				'create_date' => date ( "y-m-d H:i:s", time () ) 
		);
		
		$add_dealer_recharge_log = array (
				'change_id' => DealerBiz::generateDealerAmountChangeId (),
				'dealer_recharge_id' => $dealer_recharge_id,
				'dealer_id' => $dealer_id,
				'dealer_name' => I ( 'dealer_name' ),
				'recharge_status_text' => StringBiz::getDealerRechargeTypeRevenueStatusText ( 1 ),
				'recharge_status' => 1,
				'role_type' => $role_type,
				'role_id' => $role_id,
				'role_name' => $role_name,
				'remark' => I ( 'remark' ),
				'create_user' => "whaleyinfo.order DealerController.dealerAmountApplyAction",
				'create_date' => date ( "y-m-d H:i:s", time () ) 
		);
		
		$upload_config = array (
				'maxSize' => 0,
				'rootPath' => './Public/Uploads/',
				'savePath' => 'dealer/' . $dealer_id . '/',
				'saveName' => array (
						'uniqid',
						'' 
				),
				'exts' => array (
						'jpg',
						'gif',
						'png',
						'jpeg' 
				),
				'subName' => '',
				'replace' => true 
		);
		$upload->autoSub = false;
		$upload = new \Think\Upload ( $upload_config ); // 实例化上传类
		$info = $upload->upload ();
		
		/* $add_dealer_recharge = array (
				'dealer_recharge_id' => $dealer_recharge_id,
				'dealer_id' => $dealer_id,
				'dealer_name' => I ( 'dealer_name' ),
				'audit_user_name' => cookie ( 'login_user_id' ),
				'amount_kind' => I ( 'amount_kind' ),
				'amount_type' => I ( 'amount_type' ),
				'amount' => I ( 'amount' ),
				'recharge_status' => 1,
				'remark' => I ( 'remark' ),
				'create_user' => "whaleyinfo.order DealerController.dealerAmountApplyAction",
				'create_date' => date ( "y-m-d H:i:s", time () )
		);
		
		$add_dealer_recharge_log = array (
				'change_id' => DealerBiz::generateDealerAmountChangeId (),
				'dealer_recharge_id' => $dealer_recharge_id,
				'dealer_id' => $dealer_id,
				'dealer_name' => I ( 'dealer_name' ),
				'recharge_status_text' => StringBiz::getDealerRechargeTypeRevenueStatusText ( 1 ),
				'recharge_status' => 1,
				'role_type' => $role_type,
				'role_id' => $role_id,
				'role_name' => $role_name,
				'remark' => I ( 'remark' ),
				'create_user' => "whaleyinfo.order DealerController.dealerAmountApplyAction",
				'create_date' => date ( "y-m-d H:i:s", time () )
		);
		 */
		if (! $info) {
			// 转到注册失败页面
			// redirect(C('UrlConfig.common_error_url').'?type=11&param=缺少证件照片上传(图片过大，不要超过2mb)，'.$upload->getError());
			// $error_msg="请上传文件大小不超过2M并以jpg,gif,png,jpeg格式的图片！";
			$error_msg = $upload->getError ();
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&msg=,' . $error_msg );
			return;
		}
		
		foreach ( $info as $file ) {
			
			$key = $file ['key'];
			switch ($key) {
				case 'identify_image' :
					$add_dealer_recharge['identify_image'] 		= $file ['savepath'] . $file ['savename'];
					$add_dealer_recharge['identify_image_md5']	= md5_file($upload_config['rootPath'].$file ['savepath'].$file ['savename']);
					break;
				default :
					break;
			}
		}
		
		//====== 申请唯一性校验 begin  ======
		$exist_dealer_recharge	= M('dealer_recharge')->where("dealer_id='%s' AND amount=%s AND identify_image_md5='%s'", 
				array($dealer_id, I('amount'), $add_dealer_recharge['identify_image_md5']))->find();
		if(!empty($exist_dealer_recharge)){
			$error_msg = "这个付款凭证已经申请过了，请不要重复申请！";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&msg=,' . $error_msg );
			return;
		}
		//====== 申请唯一性校验  end ======
		
		
		
		M ( 'dealer_recharge' )->add ( $add_dealer_recharge );
		M ( 'dealer_recharge_status_change_log' )->add ( $add_dealer_recharge_log );
		
		$error_msg = "余额申请已提交!";
		redirect ( C ( 'AdminConfig.info_page' ) . '?type=202&is_show_button=2&msg=' . $error_msg );
		return;
	}
	
	public function saleDepartmentAudit() {
		$dealer_recharge_id = I ( 'dealer_recharge_id' );
		$type = I ( 'type' );
		$dealer_recharge_en = M ( 'dealer_recharge' )->where ( "dealer_recharge_id='%s'", $dealer_recharge_id )->find ();
		if (empty ( $dealer_recharge_en )) {
			
			$error_msg = "记录不存在,请检查!";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
			return;
		}
		
		if ($dealer_recharge_en ['recharge_status'] != 1) {
			
			$error_msg = "充值申请状态非法,请检查!";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
			return;
		}
		
		// 查看登录用户是否为业务员
		$sale_name = cookie ( 'login_user_id' );
		$sale_en = M ( 'sale_user' )->where ( "sale_name='%s'", $sale_name )->find ();
		// 业务员登录
		if (! empty ( $sale_en )) {
			
			$role_type = 2;
			$role_id = $sale_en ['sale_id'];
			$role_name = $sale_en ['sale_name'];
		} else {
			// 管理员角色
			$role_type = 1;
			$whaley_user = M ( 'whaley_user', '', 'DB_whaley_system' )->where ( "user_name='%s'", $sale_name )->find ();
			$role_id = $whaley_user ['user_id'];
			$role_name = $whaley_user ['user_name'];
		}
		
		switch ($type) {
			
			case 1 :
				// 销售管理部审批成功 1->3
				M ( 'dealer_recharge' )->where ( "dealer_recharge_id='%s'", $dealer_recharge_id )->setField ( "recharge_status", 3 );
				$add_dealer_recharge_log = array (
						'change_id' => DealerBiz::generateDealerAmountChangeId (),
						'dealer_recharge_id' => $dealer_recharge_id,
						'dealer_id' => $dealer_recharge_en ['dealer_id'],
						'dealer_name' => $dealer_recharge_en ['dealer_name'],
						'recharge_status_text' => StringBiz::getDealerRechargeTypeRevenueStatusText ( 3 ),
						'recharge_status' => 3,
						'role_type' => $role_type,
						'role_id' => $role_id,
						'role_name' => $role_name,
						'remark' => I ( 'remark' ),
						'create_user' => "whaleyinfo.order DealerController.saleDepartmentAudit",
						'create_date' => date ( "y-m-d H:i:s", time () ) 
				);
				M ( 'dealer_recharge_status_change_log' )->add ( $add_dealer_recharge_log );
				$error_msg = "销售管理部审批成功!";
				redirect ( C ( 'AdminConfig.info_page' ) . '?type=202&is_show_button=2&msg=' . $error_msg );
				return;
			case 2 :
				// 销售管理部审批失败 1->11
				$remark = I ( 'remark' );
				if (empty ( $remark )) {
					
					$error_msg = "请输入审批人意见!";
					redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
					return;
				}
				M ( 'dealer_recharge' )->where ( "dealer_recharge_id='%s'", $dealer_recharge_id )->setField ( "recharge_status", 11 );
				$add_dealer_recharge_log = array (
						'change_id' => DealerBiz::generateDealerAmountChangeId (),
						'dealer_recharge_id' => $dealer_recharge_id,
						'dealer_id' => $dealer_recharge_en ['dealer_id'],
						'dealer_name' => $dealer_recharge_en ['dealer_name'],
						'recharge_status_text' => StringBiz::getDealerRechargeTypeRevenueStatusText ( 11 ),
						'recharge_status' => 11,
						'role_type' => $role_type,
						'role_id' => $role_id,
						'role_name' => $role_name,
						'remark' => I ( 'remark' ),
						'create_user' => "whaleyinfo.order DealerController.saleDepartmentAudit",
						'create_date' => date ( "y-m-d H:i:s", time () ) 
				);
				M ( 'dealer_recharge_status_change_log' )->add ( $add_dealer_recharge_log );
				$error_msg = "销售管理部审批已拒绝!";
				redirect ( C ( 'AdminConfig.info_page' ) . '?type=202&is_show_button=2&msg=' . $error_msg );
				return;
			default :
				$error_msg = "操作非法,请检查!";
				redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
				return;
		}
	}
	public function financeDepartmentAudit() {
		$dealer_recharge_id = I ( 'dealer_recharge_id' );
		$type = I ( 'type' );
		$dealer_recharge_en = M ( 'dealer_recharge' )->where ( "dealer_recharge_id='%s'", $dealer_recharge_id )->find ();
		if (empty ( $dealer_recharge_en )) {
			
			$error_msg = "记录不存在,请检查!";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
			return;
		}
		
		// if ($dealer_recharge_en ['recharge_status'] != 3) {//销售管理部已审批
		if ($dealer_recharge_en ['recharge_status'] != 1 ) { // 财务直接审批
			$error_msg = "充值申请状态非法,请检查!";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
			return;
		}
		
		// 查看登录用户是否为业务员
		$sale_name = cookie ( 'login_user_id' );
		$sale_en = M ( 'sale_user' )->where ( "sale_name='%s'", $sale_name )->find ();
		// 业务员登录
		if (! empty ( $sale_en )) {
			
			$role_type = 2;
			$role_id = $sale_en ['sale_id'];
			$role_name = $sale_en ['sale_name'];
		} else {
			// 管理员角色
			$role_type = 1;
			$whaley_user = M ( 'whaley_user', '', 'DB_whaley_system' )->where ( "user_name='%s'", $sale_name )->find ();
			$role_id = $whaley_user ['user_id'];
			$role_name = $whaley_user ['user_name'];
		}
		
		switch ($type) {
			
			case 3 :
				// 财务部审批成功 3->4
				M ( 'dealer_recharge' )->where ( "dealer_recharge_id='%s'", $dealer_recharge_id )->setField ( "recharge_status", 4 );
				$dealer_en = M ( 'dealer_info' )->where ( "dealer_id='%s'", $dealer_recharge_en ['dealer_id'] )->find ();
				// 插入余额表
				$dealer_amount = array (
						"dealer_amount_id" => DealerBiz::generateDealerAmountId (),
						"dealer_id" => $dealer_recharge_en ['dealer_id'],
						"dealer_name" => $dealer_recharge_en ['dealer_name'],
						"amount_kind" => $dealer_recharge_en ['amount_kind'],
						"amount_type" => $dealer_recharge_en ['amount_type'],
						"amount" => $dealer_recharge_en ['amount'],
						"begin_amount" => $dealer_en ['amount'],
						"end_amount" => $dealer_recharge_en ['amount'] + $dealer_en ['amount'],
						"remark" => I ( 'remark' ),
						"status" => 1,
						'create_user' => "whaleyinfo.order DealerBiz.financeDepartmentAudit",
						'create_date' => date ( "y-m-d H:i:s", time () ) 
				);
				M ( 'dealer_amount' )->add ( $dealer_amount );
				// 更新审批日志表
				$dealer_recharge_log = array (
						'change_id' => DealerBiz::generateDealerAmountChangeId (),
						'dealer_recharge_id' => $dealer_recharge_id,
						'dealer_id' => $dealer_recharge_en ['dealer_id'],
						'dealer_name' => $dealer_recharge_en ['dealer_name'],
						'recharge_status_text' => StringBiz::getDealerRechargeTypeRevenueStatusText ( 4 ),
						'recharge_status' => 4,
						'role_type' => $role_type,
						'role_id' => $role_id,
						'role_name' => $role_name,
						'remark' => I ( 'remark' ),
						'create_user' => "whaleyinfo.order DealerController.financeDepartmentAudit",
						'create_date' => date ( "y-m-d H:i:s", time () ) 
				);
				M ( 'dealer_recharge_status_change_log' )->add ( $dealer_recharge_log );
				// 财务审批完毕4->5 充值完成
				M ( 'dealer_recharge' )->where ( "dealer_recharge_id='%s'", $dealer_recharge_id )->setField ( "recharge_status", 5 );
				
				// 更新充值日志表
				$dealer_recharge_log1 = array (
						'change_id' => DealerBiz::generateDealerAmountChangeId (),
						'dealer_recharge_id' => $dealer_recharge_id,
						'dealer_id' => $dealer_recharge_en ['dealer_id'],
						'dealer_name' => $dealer_recharge_en ['dealer_name'],
						'recharge_status_text' => StringBiz::getDealerRechargeTypeRevenueStatusText ( 5 ),
						'recharge_status' => 5,
						'role_type' => $role_type,
						'role_id' => $role_id,
						'role_name' => $role_name,
						'remark' => I ( 'remark' ),
						'create_user' => "whaleyinfo.order DealerController.financeDepartmentAudit",
						'create_date' => date ( "y-m-d H:i:s", time () ) 
				);
				M ( 'dealer_recharge_status_change_log' )->add ( $dealer_recharge_log1 );
				
				// 更新经销商表余额字段
				M ( 'dealer_info' )->where ( "dealer_id='%s'", dealer_recharge_en ['dealer_id'] )->setField ( "amount", $dealer_en ['amount'] + $dealer_recharge_en ['amount'] );


                //邮件通知

                MailBiz::callMailApi ( C ( 'EmailConfig.DealerRechargeSuccessReceiverList' ),  C ( 'EmailConfig.DealerRechargeSuccessSubject' ).'【充值成功】', '经销商：' .$dealer_recharge_en ['dealer_name']. ", 充值".$dealer_recharge_en ['amount'].",财务已审批！");
                $error_msg = "财务部审批成功!";
                redirect ( C ( 'AdminConfig.info_page' ) . '?type=202&is_show_button=2&msg=' . $error_msg );
                return;
            case 4 :
                // 财务部审批失败 3->11
                $remark = I ( 'remark' );
                if (empty ( $remark )) {$
					
					$error_msg = "请输入审批人意见!";
					redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
					return;
				}
				M ( 'dealer_recharge' )->where ( "dealer_recharge_id='%s'", $dealer_recharge_id )->setField ( "recharge_status", 11 );
				$add_dealer_recharge_log = array (
						'change_id' => DealerBiz::generateDealerAmountChangeId (),
						'dealer_recharge_id' => $dealer_recharge_id,
						'dealer_id' => $dealer_recharge_en ['dealer_id'],
						'dealer_name' => $dealer_recharge_en ['dealer_name'],
						'recharge_status_text' => StringBiz::getDealerRechargeTypeRevenueStatusText ( 11 ),
						'recharge_status' => 11,
						'role_type' => $role_type,
						'role_id' => $role_id,
						'role_name' => $role_name,
						'remark' => I ( 'remark' ),
						'create_user' => "whaleyinfo.order DealerController.financeDepartmentAudit",
						'create_date' => date ( "y-m-d H:i:s", time () ) 
				);
				M ( 'dealer_recharge_status_change_log' )->add ( $add_dealer_recharge_log );
				
				MailBiz::callMailApi ( C ( 'EmailConfig.DealerRechargeSuccessReceiverList' ),  C ( 'EmailConfig.DealerRechargeSuccessSubject' ).'【无效充值】', '经销商：' .$dealer_recharge_en ['dealer_name']. ", 充值".$dealer_recharge_en ['amount'].",无效充值！备注：".$remark);
				$error_msg = "财务部审批已拒绝!";
				redirect ( C ( 'AdminConfig.info_page' ) . '?type=202&is_show_button=2&msg=' . $error_msg );
				return;
			default :
				$error_msg = "操作非法,请检查!";
				redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
				return;
		}
	}
	
	
	public function navCalcDealerCashBackAmount(){
		
		$this->display("dealer/dealeracashbackamountcalc");
		
	}
	
	
	public function shipDealerCashBackAmountExcel(){
		
		// 参数处理
		$params_en = array (
				
				//'dealer_name' => I ( 'dealer_name' ),
				
				
				'start_date' => I ( 'start_date' ),
				'end_date' => I ( 'end_date' ),
				
		);
		
		Vendor ( 'phpExcel.PHPExcel' );
		$objPHPExcel = OrderBiz::shipDealerCashBackAmount ( $params_en );
		
		// echo $objPHPExcel.I('start_date');
		// return ;
		// 输出到浏览器
		// $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
		$objWriter = new \PHPExcel_Writer_Excel5 ( $objPHPExcel );
		
		header ( "Pragma: public" );
		header ( "Expires: 0" );
		header ( "Cache-Control:must-revalidate, post-check=0, pre-check=0" );
		header ( "Content-Type:application/force-download" );
		header ( "Content-Type:application/vnd.ms-execl" );
		header ( "Content-Type:application/octet-stream" );
		header ( "Content-Type:application/download" );
		header ( 'Content-Disposition:attachment;filename="cashresult.xls"' );
		header ( "Content-Transfer-Encoding:binary" );
		$objWriter->save ( 'php://output' );
		
	}
	
	public  function  ordercancelpart(){
		
		$order_id = I('order_id');
		$oid = I('oid');
		$rma_remark= I('remark');
		$order_en = M('order_info')->where("order_id ='%s'",$order_id)->find();
		$order_payment_en  =M('order_payment')->where("order_id ='%s'",$order_id)->find();
		$order_detail = M('order_detail')->where("order_id ='%s' and oid ='%s'",$order_id,$oid)->find();
		$order_need_deliver_lst=M('order_detail')->where("order_id ='%s' and (qty != ship_qty  and  qty!=rma_qty)",$order_id)->select();
		$dealer_en = M('dealer_info')->where("dealer_id='%s'",$order_en['buyer_alipay_no'])->find();
		$paras_en = array(
				'sku_id'=>$order_detail['sku_id'],
		);
		$product_en=RmaBiz::queryProductBySkuPara($paras_en);
		$operator_name=cookie ( 'login_user_id' );
		$operator = M ( 'whaley_user', '', 'DB_whaley_system' )->where ( "user_name='%s'", $operator_name )->find ();
		
		
		//已支付或部分发货的订单且货物尚未发出才可以取消次明细项
		if($order_en['order_status']==22||$order_en['order_status']==33 ){
				
			if($order_detail['qty'] == $order_detail['ship_qty']){
				$error_msg = "已支付的订单且货物尚未发出才可以取消次明细项!请检查";
				redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
				return;
			}

			
			
		//上传凭证支付方式和余额支付退换余额	
		 if($order_en['order_type'] == 8  && $order_en['payment_status'] == 1){
		 	$d_account_amount=0;
		 	$d_cashback_account_amount=0;
		 	//金额进行分摊
		 	//$d_account_amount=round($order_detail['payment_amount']*$order_payment_en['account_amount']/$order_en['payment_amount'],2);
		 	//$d_cashback_account_amount=round($order_detail['payment_amount']*$order_payment_en['cashback_account_amount']/$order_en['payment_amount'],2);
		 	if($order_en['payment_method']==40){//支付凭证方式退款，直接退商品实付金额到余额账户，后返余额不用
		 		$d_account_amount=$order_detail['payment_amount'];
		 		
		 	}
		 	
		 	if($order_en['payment_method']==30){//余额支付方式退款，直接退该商品已分摊的余额部分的钱额到余额账户，后返余额不用
		 		$d_account_amount=$order_detail['account_amount'];
		 		 
		 	}
		 	
		 	if($order_en['payment_method']==31){//余额支付+后返余额方式退款，直接退该商品已分摊的余额部分的钱到余额账户，后返余额直接退已分摊的后返余额部分的钱到后返余额账户
		 		$d_account_amount=$order_detail['account_amount'];
		 		$d_cashback_account_amount=$order_detail['cashback_account_amount'];
		 	
		 	}
		 	
		 	
		 	
		 	
		 	
		 	// ============= 1、变更余额 begin =============
		 	$dealer_new_amount = $dealer_en['amount'] + $d_account_amount;
		 	if($d_account_amount>0){
		 		M('dealer_info')
		 		->where("dealer_id='%s'", $dealer_en['dealer_id'])
		 		->setField('amount', $dealer_new_amount);
		 	
		 	
		 	//插入经销商余额表
		 	$dealer_amount = array(
		 			"dealer_amount_id"	=> DealerBiz::generateDealerAmountId(),
		 			"dealer_id"   =>$dealer_en['dealer_id'],
		 			"dealer_name" =>$dealer_en['dealer_name'],
		 			"amount_kind" =>1,//减少
		 			"amount_type" =>15,//订单取消余额退回
		 			"amount"      =>$d_account_amount,//订单金额
		 			"begin_amount"=>$dealer_en['amount'],
		 			"end_amount"  =>$dealer_new_amount,
		 			"order_id"    =>$order_id,
		 			"remark" =>"订单部分取消",
		 			"status" =>1,//有效
		 			'create_user' => "whaleyinfo.order Dealer.ordercancelpart",
		 			'create_date' => date ( "y-m-d H:i:s", time () )
		 	);
		 	M('dealer_amount')->add($dealer_amount);
		 }
		 	if($order_en['payment_method'] == 31){
		 		$dealer_cashback_amount = $d_cashback_account_amount;
		 		if($dealer_cashback_amount > 0){
		 			$dealer_new_cashback_amount = $dealer_en['cashback_amount'] + $dealer_cashback_amount;
		 			M('dealer_info')
		 			->where("dealer_id='%s'",  $dealer_en['dealer_id'])
		 			->setField('cashback_amount', $dealer_new_cashback_amount);
		 			$dealer_cashback_amount = array(
		 					"dealer_amount_id"	=> DealerBiz::generateDealerAmountId(),
		 					"dealer_id"   =>$dealer_en['dealer_id'],
		 					"dealer_name" =>$dealer_en['dealer_name'],
		 					"amount_kind" =>1,//增加
		 					"amount_type" =>15,//订单取消余额退回
		 					"amount"      =>$dealer_cashback_amount,
		 					"begin_amount"=>$dealer_en['cashback_amount'],
		 					"end_amount"  =>$dealer_new_cashback_amount,
		 					"order_id"    =>$order_id,
		 					"remark" =>"订单部分取消",
		 					"status" =>1,//有效
		 					'create_user' => "whaleyinfo.order Dealer.ordercancelpart",
		 					'create_date' => date ( "y-m-d H:i:s", time () )
		 			);
		 			M('dealer_cashback_amount')->add($dealer_cashback_amount);
		 		}
		 	}
		 	
		 	//生成退换货记录
		 	
		 	$rma_qty=0;
		 	$rma_amount=0;
		 	$order_rma_id = RmaBiz::generateOrderRmaId();
		 	$rma_en=array(
		 			'order_rma_id' =>$order_rma_id,
		 			'order_id'=>I('order_id'),
		 			'rma_type' =>1,//退货
		 			'user_type'=>1,//经销商
		 			'user_id' =>$dealer_en['dealer_id'],
		 			'user_name'=>$dealer_en['dealer_name'],
		 			'operator_id' =>$operator['user_id'],
		 			'operator_name'=>$operator_name,
		 			'rma_reason_type'=>3,
		 			'rma_reason_remark'=>$rma_remark,
		 			//'invoice_serial_no'=>I('invoice_serial_no'),
		 			'order_date' =>$order_en['order_date'],
		 			'rma_date' =>date('y-m-d H:i:s',time()),
		 			'rma_status' =>10,
		 			'consignee_name' =>$order_en['consignee_name'],
		 			'consignee_cellphone'=>$order_en['consignee_cellphone'],
		 			'consignee_province_id' => $order_en['consignee_province_id'],
		 			'consignee_province' => $order_en['consignee_province'] ,
		 			'consignee_city_id' => $order_en['consignee_city_id' ],
		 			'consignee_city' => $order_en[ 'consignee_city' ],
		 			'consignee_district_id'=>$order_en['consignee_district_id'],
		 			'consignee_district'=>$order_en['consignee_district'],
		 			'consignee_address'=>$order_en['consignee_address'],
		 			'consignee_zip'=>$order_en['consignee_zip'],
		 			'create_user' => "whaleyinfo.order Dealer.ordercancelpart",
		 			'create_date' => date ( "y-m-d H:i:s", time () )
		 	);
		 	
		 	
		 	$rma_d_en = Array(
		 			'order_rma_detail_id' => RmaBiz::generateOrderRmaDetailId(),
		 			'order_rma_id'=>$order_rma_id,
		 			'order_id' =>$order_id,
		 			'order_detail_id'=>$oid,
		 			'sku_id' => $product_en['sku_id'],
		 			'sku_name'=>$product_en['sku_name'],
		 			'product_id'=>$product_en['product_id'],
		 			'product_name'=>$product_en['product_name'],
		 			'rma_status' =>10,
		 			'rma_qty' =>$order_detail['qty'],
		 			'sale_price'=>$order_detail['goods_payment_amount'],
		 			'account_amount'=>$order_detail['account_amount'],
		 			'cashback_account_amount' =>$order_detail['cashback_account_amount'],
		 			'rma_amount'=>$order_detail['account_amount']+$order_detail['cashback_account_amount'],
		 			'material_no'=>$product_en['material_no'],
		 			'material_desc' =>$product_en['material_desc'],
		 			//'product_old_sn' =>$old_sns[$i],
		 			'create_user' => "whaleyinfo.order Dealer.ordercancelpart",
		 			'create_date' => date ( "y-m-d H:i:s", time () )
		 			);
		 	
		 	
		 	$rma_qty+=$order_detail['qty'];
		 	$rma_amount =$order_detail['account_amount']+$order_detail['cashback_account_amount']; 
		 	
		 	$rma_en['rma_qty']=$rma_qty;
		 	$rma_en['rma_amount'] =$rma_amount;
		 	$rma_en['account_amount']+=$order_detail['account_amount'];
		 	$rma_en['cashback_account_amount'] +=$order_detail['cashback_account_amount'];
		 	
		 	M('order_rma_detail')->add($rma_d_en);
		 	M('order_rma')->add($rma_en);
		 	//更新已退的数量
		 	
		 	$odetail= array(
		 	'rma_qty' =>$order_detail['qty'],
		 	'is_refund'=>1,
		 	);
		 	
		 	
		 	M('order_detail')->where("order_id ='%s' and oid ='%s'",$order_id,$oid)->save($odetail);
		 	
		 	M('order_info')->where("order_id ='%s'",$order_id)->setField("rma_qty",$order_detail['qty']+$order_en['rma_qty']);
		 	if($order_en['order_status']==22)
		 	{
		 		
		 		if(sizeof($order_need_deliver_lst)==1){//更改整张订单为全部取消
		 			
		 			
		 			// 写订单数据库
		 			M ( 'order_info' )->where ( "order_id='%s'", $order_id )->setField("order_status",52);
		 			// 写订单日志表
		 			$order_change_log = array (
		 					"order_id" => $order_id,
		 					"order_status" => 54,
		 					"order_status_text" => '客服分次全部取消',
		 					"create_user" => 'whaleyinfo.order dealer.ordercancelpart',
		 					"create_date" => date ( "y-m-d H:i:s", time () )
		 			);
		 			M ( 'order_status_change_log' )->data ( $order_change_log )->add ();
		 			
		 		}
		 		
		 	}else{
		 		
		 		if(sizeof($order_need_deliver_lst)==1){//更改订单为全部发货
		 			
		 			// 写订单数据库
		 			M ( 'order_info' )->where ( "order_id='%s'", $order_id )->setField("order_status",31);
		 			// 写订单日志表
		 			$order_change_log = array (
		 					"order_id" => $order_id,
		 					"order_status" => 31,
		 					"order_status_text" => '已全部发货',
		 					"create_user" => 'whaleyinfo.order dealer.ordercancelpart',
		 					"create_date" => date ( "y-m-d H:i:s", time () )
		 			);
		 			M ( 'order_status_change_log' )->data ( $order_change_log )->add ();
		 		}
		 	}
		 	
		 	
		 	$order_rma_status_change_log_en = array(
		 			'order_rma_id'	=> $order_rma_id,
		 			'rma_status'	=> 10,
		 			'rma_status_text'	=> '已提交',
		 			'remark'		=> '',
		 			'create_user' => "whaleyinfo.order Dealer.ordercancelpart",
		 			'create_date' => date ( "y-m-d H:i:s", time () )
		 	);
		 	
		 	
		 	M('order_rma_status_change_log')->add($order_rma_status_change_log_en);
		 	
		 	$order_rma_status_change_log_en = array(
		 			'order_rma_id'	=> $order_rma_id,
		 			'rma_status'	=> 18,
		 			'rma_status_text'	=> '财务已审核',
		 			'remark'		=> '',
		 			'create_user' => "whaleyinfo.order Dealer.ordercancelpart",
		 			'create_date' => date ( "y-m-d H:i:s", time () )
		 	);
		 	M('order_rma_status_change_log')->add($order_rma_status_change_log_en);
		 	
		 	M('order_rma')->where("order_rma_id='%s'",$order_rma_id)->setField("rma_status",18);
		 	M('order_rma_detail')->where("order_rma_id='%s'",$order_rma_id)->setField("rma_status",18);
		 	$order_rma_status_change_log_en = array(
		 			'order_rma_id'	=> $order_rma_id,
		 			'rma_status'	=> 35,
		 			'rma_status_text'	=> '已完成',
		 			'remark'		=> '',
		 			'create_user' => "whaleyinfo.order Dealer.ordercancelpart",
		 			'create_date' => date ( "y-m-d H:i:s", time () )
		 	);
		 	M('order_rma_status_change_log')->add($order_rma_status_change_log_en);
		 	
		 	M('order_rma')->where("order_rma_id='%s'",$order_rma_id)->setField("rma_status",35);
		 	M('order_rma_detail')->where("order_rma_id='%s'",$order_rma_id)->setField("rma_status",35);
		 	$error_msg = "订单部分取消成功!";
		 	redirect ( C ( 'AdminConfig.info_page' ) . '?type=202&is_show_button=2&msg=' . $error_msg );
		 	return;
		 	

		  }
		
		}else{
			
			$error_msg = "已支付或者部分发货的订单且货物尚未发出才可以取消次订单明细项!请检查订单状态";
			redirect ( C ( 'AdminConfig.error_info_page' ) . '?type=202&is_show_button=2&msg=,' . $error_msg );
			return;
			
		}
	
	}
	
	/**
	 * Description: 经销商发票开具
	 * @version 2016年11月7日 下午2:59:44 
	 * @author lin.yujiao@whaley.cn
	 */
	public function paperInvList(){
		$this->assign('page_name', "经销商发票开具");
		$this->display("dealer/paperInvList");
	}
	/**
	 * Description: 经销商发票开具
	 * @version 2016年11月7日 下午2:59:44 
	 * @author lin.yujiao@whaley.cn
	 */
	public function paperInvPreview(){
		$arr_oids = explode(",",I('oids'));
		$msg = '';
		$oids_tmp = array();
		$lst_preview = OrderInfoBiz::paperInvPreview($arr_oids,$msg, $oids_tmp);
		$this->assign('lst_preview', $lst_preview);
		$this->assign('lst_invoice', json_encode($lst_preview));
		//去重
		$oids = array_unique($oids_tmp);
		$this->assign('oids', json_encode($oids));
		$this->assign('msg', $msg);
		$this->assign('page_name', "经销商发票预览");
		$this->display("dealer/paperInvPreview");
	}
	
	
	
	public function ordercancelpartdetail(){
		
		$order_id=I('order_id');
		$oid = I('oid');
		
		$this->assign("order_id",$order_id);
		$this->assign("oid",$oid);
		$this->display("dealer/ordercancelpartdetail");
	}
	
	
	
	public function  shipDealerCashBackAmountInfoExcel(){
	
		// 参数处理
		
		$params_en = array (
				'dealer_id' => I ( 'dealer_id' ),
				'amount_type' => I ( 'amount_type' ),
				'dealer_channel' => I ( 'dealer_channel' ),
				'start_date' => I('start_date'),
				'end_date' => I('end_date'),
		);
		
		Vendor ( 'phpExcel.PHPExcel' );
		$objPHPExcel = DealerBiz::shipDealerCashBackAmountExcel( $params_en );
		
		// 输出到浏览器
		// $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
		$objWriter = new \PHPExcel_Writer_Excel5 ( $objPHPExcel );
		
		header ( "Pragma: public" );
		header ( "Expires: 0" );
		header ( "Cache-Control:must-revalidate, post-check=0, pre-check=0" );
		header ( "Content-Type:application/force-download" );
		header ( "Content-Type:application/vnd.ms-execl" );
		header ( "Content-Type:application/octet-stream" );
		header ( "Content-Type:application/download" );
		header ( 'Content-Disposition:attachment;filename="dealercashbackamount.xls"' );
		header ( "Content-Transfer-Encoding:binary" );
		$objWriter->save ( 'php://output' );
		
	}
	
	public function  shipDealerAmountInfoExcel(){
	
		// 参数处理
	
		$params_en = array (
				'dealer_id' => I ( 'dealer_id' ),
				'amount_type' => I ( 'amount_type' ),
				'dealer_channel' => I ( 'dealer_channel' ),
				'start_date' => I('start_date'),
				'end_date' => I('end_date'),
		);
	
		Vendor ( 'phpExcel.PHPExcel' );
		$objPHPExcel = DealerBiz::shipDealerAmountExcel( $params_en );
	
		// 输出到浏览器
		// $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
		$objWriter = new \PHPExcel_Writer_Excel5 ( $objPHPExcel );
	
		header ( "Pragma: public" );
		header ( "Expires: 0" );
		header ( "Cache-Control:must-revalidate, post-check=0, pre-check=0" );
		header ( "Content-Type:application/force-download" );
		header ( "Content-Type:application/vnd.ms-execl" );
		header ( "Content-Type:application/octet-stream" );
		header ( "Content-Type:application/download" );
		header ( 'Content-Disposition:attachment;filename="dealeramount.xls"' );
		header ( "Content-Transfer-Encoding:binary" );
		$objWriter->save ( 'php://output' );
	
	}
}



